简体   繁体   中英

How to extract Python object from JSON object?

I'm able to get a JSON string from a Python object as is :

def myserialize(obj):
    return obj.__dict__

class A:
    def __init__(self):
        self._filename = AString()
        self._size = AnInt()
        self.objectString = ObjectContainingAString()
        self.arrayOfObject = ....
    def get_json_string(self):
        return json.dumps(self.__dict__,default=myserialize,indent=4,sort_keys=True)

The JSON output looks like this

{
    "_filename" : "value_of_string"
    "_size" : value_of_int
    "objectString": {
        "string" : "value_of_string"
    }
    "arrayOfObject" : [
         {
             "obj1" : {
             ...
             }
         },
         {
             "obj2"...
         }
     ]
}

This is exactly what I want ! A simple way to convert Python "complex" object to JSON string.

Problem : But now, I'd like to convert this string to the same "complex" Python object !

Scenario: The scenario is that I have a few more (different) "complex" objects that I want to convert back and forth from a JSON string.

It's okay if the solution you give must include an ID in the string somehow stating "this is a JSON string for an object of type XYZ only" since I only have a few "complex" objects (5/6).

EDIT 1

Complete scenario : I have 6 binary files containing configuration for an embedded software. This is clearly not human-readable.

I'm currently using Python to parse the binary file and extract its content to get a human-readable version. (JSON or something else !) JSON at least has the advantage of converting the Python object containg all the info about one config file in one line.

People should now be able to edit a few values in the (JSON or whatever) text configuration file.

I want to be able to convert the text file back to the corresponding Python object, and serialize it to get a modified binary file !

END OF EDIT

The simplest re-usable solution I see involves two steps:

  1. parse the json back into a python dictionary (this handles type conversions), and can be done outside of your class's constructor
  2. optionally feed a python dictionary into your class's constructor and, when specified, use it to populate your class's fields with setattr

Here are the same thoughts expressed as python code:

class A:
    def __init__(self, input_dict=None):

        if input_dict is not None:
            for k, v in input_dict.items():
                setattr(self, k, v)
        else:

            self._filename = AString()
            self._size = AnInt()
            self.objectString = ObjectContainingAString()
            self.arrayOfObject = ....

        ...

# Assume we have a list of json strings created by your json export
# Now parse json strings and turn them into objects of class A
for json_str in json_strs:
  new_object = A(input_dict=json.loads(json_str))
  # Do something with new_object...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM