我想将解析后的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
}]
}
}
Run Code Online (Sandbox Code Playgroud)
我试图创建一个名为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'])
Run Code Online (Sandbox Code Playgroud)
然后我尝试使用object_hook函数将数据加载到对象中:
for item in data['Output']['Rect']:
region = json.loads(item, object_hook=obj_creator)
Run Code Online (Sandbox Code Playgroud)
但我发现它有错误说
TypeError: the JSON object must be str, bytes or bytearray, not 'dict'
Run Code Online (Sandbox Code Playgroud)
实际上我知道如果我的数据没有嵌套,如何将对象分配给python对象.但我没有使用嵌套的json数据.有什么建议吗?
谢谢.
看起来你的JSON实际上是一个字典.
您可以Region轻松创建一个实例,因为dict属性和实例属性具有相同的名称,通过item用两个解压缩dict **:
regions = []
for item in data['Output']['Rect']:
regions.append( Region(**item) )
for region in regions:
print( region )
Run Code Online (Sandbox Code Playgroud)
输出:
{"x"=34, "y"=51, "width"=100, "height"=100}
{"x"=14, "y"=40, "width"=4, "height"=6}
Run Code Online (Sandbox Code Playgroud)
(之后我已经改变了__str__到:)
def __str__(self):
return '{{"x"={}, "y"={}, "width"={}, "height"={}}}'.format(self.x, self.y, self.width, self.height)
Run Code Online (Sandbox Code Playgroud)