skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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 own TypeVars. Maybe this is what you are looking for.

    from typing import Generic, TypeVar
    import json
    
    SerializableField = TypeVar('SerializableField', str, int, float, bool)
    Serializable = TypeVar('Serializable',
                           dict[str, SerializableField],
                           list[SerializableField],
                           tuple[SerializableField],
                           set[SerializableField],
                           SerializableField)
    
    
    class JSONStack(Generic[Serializable]):
        def __init__(self, values: Serializable) -> None:
            self.values = values
    
        def __repr__(self):
            return f"JSONStack({self.values})"
    
    
    values: Serializable = json.loads('{"a": 1, "b": 2, "c": 3}')
    
    print(JSONStack(values))
    

    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 reason json.loads return Any and not a specific datatype.

    Lastly if you have a simple use case then using Generic and TypeVar is huge overhead anyway.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search