简体   繁体   中英

Convert json to python obj

I'd like to convert the parsed json data to python object.

here is my json format:

{
   "Input":{
      "filename":"abg.png",
      "fileSize":123456
   },
   "Output":{
      "filename":"img.png",
      "fileSize":1222,
      "Rect":[
         {
            "x":34,
            "y":51,
            "width":100,
            "height":100
         },
         {
            "x":14,
            "y":40,
            "width":4,
            "height":6
         }]
   }
}   

I tried to create a class named Region

class Region:
    def __init__(self, x, y, width, height):
        self.x=x
        self.y=y
        self.width=width
        self.height=height

    def __str__(self):
        return '{{"x"={1}, "y"={2}, "width"={3}, "height"={4}}'.format(self.left, self.top, self.width, self.height)

def obj_creator(d):
    return Region(d['x'], d['y'], d['width'], d['height'])

I then tried to load the data into the object using the object_hook function:

for item in data['Output']['Rect']:
    region = json.loads(item, object_hook=obj_creator)

but i found that it got the error saying that

TypeError: the JSON object must be str, bytes or bytearray, not 'dict'

Actually I know how to assign the object to python object if my data is not nested. But I failed to do so with my nested json data. Any advise?

Thanks.

Looks as if your JSON is actually a dict.

You can create an instance of Region easily, since the dict properties and the instance attributes have the same name, by unpacking the dict item with two ** :

regions = []
for item in data['Output']['Rect']:
    regions.append( Region(**item) )
for region in regions:
    print( region )

Output:

{"x"=34, "y"=51, "width"=100, "height"=100}
{"x"=14, "y"=40, "width"=4, "height"=6}

( after I have changed your __str__ to: )

def __str__(self):
    return '{{"x"={}, "y"={}, "width"={}, "height"={}}}'.format(self.x, self.y, self.width, self.height)

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