#jsondecoder

tord_dellsen@diasp.eu

#Python and #JSON question:

While decoding a JSON object in Python, which is part of a list in JSON, can the name of the list be accessed?

Context

The reason i'd like to do this is because i want to have lists of items of the same type, and avoid storing the object type for each element. Instead i would like to store the type for the whole list and, i could do that by (for example) adding a suffix to the name of the list

What i do now

Code:

from_file_dict: dict = json.load(read_file, object_hook=my_decode)


def my_decode(dct: dict):
    if JSON_OBJ_TYPE in dct and dct[JSON_OBJ_TYPE] == MyClass.__name__:
        my_class_obj = MyClass(dct["id"], dct["attribute_example_one"], dct["attribute_example_two"])
        return my_class_obj
    # ... elif other object types
    return dct

Example data:

{
  "example_list": [
    {
      "__obj_type__": "MyClass"
      "id": 1,
      "attribute_example_one": "Dennis Moore",
      "attribute_example_two": 42,
    },
    {
      "__obj_type__": "MyClass"
      "id": 2,
      "attribute_example_one": "Lupines",
      "attribute_example_two": 3,
    },
}

#python #json #jsondecoder

Posted here on stackoverflow, but my experience is unfortunately not the best when it comes to that network: https://stackoverflow.com/q/74081608/2525237