0

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.

1
  • 3
    Seems like what you are trying to manipulate is already a Python dictionary. Did you try to print it? Commented Jun 26, 2018 at 12:55

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Great, thanks. Just a reverse question. What if I got the regions list, and then I want to convert that directly to a json object. I used the method dumps, it works for individual region object, but not the whole list. Any direct way to do so? Thanks.
@user6539552 this might help you: stackoverflow.com/questions/26033239/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.