It is my understanding that json.load
returns any
.
I do not believe I can change the built-in typing, but I think it would be better to use more specific typing in my programs, since not all objects are JSON serializable. However, such list would be long and repetitive.
Are there any recommendations?
2
Answers
Serialization and deserialization in python is done following these rules:
python – json:
dict – object
list – array
tuple – array
str – string
int – number
float – number
True – true
False – false
None – null
You should not expect any other values, most of the time you should know if the json data is a dictionary, a list of dictionary or whatever.
If your problem is typing you could verify that loading your data returns a dictionary or a list and returning that add dict or list as typing.
If I understand correctly the issue is that json.loads returns a typing
Any
. Since that is ambigious you want a more robust solution to this. There are ways to define your ownTypeVars
. Maybe this is what you are looking for.however, use this kind of solution with caution. This can be useful if you have known or limited use case but i do not recommend this for generic applications as
JSON
can be quite complex. There is a reasonjson.loads
returnAny
and not a specific datatype.Lastly if you have a simple use case then using
Generic
andTypeVar
is huge overhead anyway.