首页 > 解决方案 > 将json转换为python obj

问题描述

我想将解析的 json 数据转换为 python 对象。

这是我的 json 格式:

{
   "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
         }]
   }
}   

我试图创建一个名为 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'])

然后我尝试使用 object_hook 函数将数据加载到对象中:

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

但我发现它有错误说

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

实际上,如果我的数据没有嵌套,我知道如何将对象分配给 python 对象。但是我没有用我的嵌套 json 数据这样做。有什么建议吗?

谢谢。

标签: pythonjson

解决方案


看起来好像您的 JSON 实际上是一个字典。

您可以轻松地创建一个实例,因为 dict 属性和实例属性具有相同的名称,方法是使用两个Region解包 dict :item**

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

输出:

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

(在我将您更改__str__为:)

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

推荐阅读