Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I type annotate JSON data in Python?

I am adding type annotations to a lot of code to make it clear to other devs what my functions and methods do. How would I type annotate a function that takes JSON data in as an argument, and returns JSON data?

(very simplified version)

def func(json_data):
    return json_data

what I want to do but with JSON instead of int:

def add_nums(a: int, b: int) -> int:
    return a+b
like image 499
Milind Sharma Avatar asked Feb 05 '26 20:02

Milind Sharma


1 Answers

Quoting from https://github.com/python/typing/issues/182#issuecomment-1320974824:

All major type checkers now support recursive type aliases by default, so this should largely work:

JSON: TypeAlias = dict[str, "JSON"] | list["JSON"] | str | int | float | bool | None

Note that because dict is invariant, you might run into some issues e.g. with dict[str, str]. For such use cases you can use cast, and if you don't need mutability, something like the following might work:

JSON_ro: TypeAlias = Mapping[str, "JSON_ro"] | Sequence["JSON_ro"] | str | > int | float | bool | None
like image 61
pradyunsg Avatar answered Feb 07 '26 09:02

pradyunsg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!