python - 将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 数据这样做。有什么建议吗?
谢谢。
解决方案
看起来好像您的 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)
推荐阅读
- java - 尝试从 SQLite DB 设置 checkedtextview 时出错
- asp.net-core-2.0 - 如何在 asp.net 核心框架中使用 DocuSign 对文档进行数字签名
- r - 从 R 中的异常库运行 time_decompose 函数时收到错误消息
- ios - 如何更改 statusBarFrame 颜色以与 Swift iOS 13 中的 NavigationController 保持相同
- c++ - C++ 通过vector.resize() 和vector.reserve() 从函数返回向量
- glob - 为什么GLOB叫GLOB?它的完整形式是什么?
- javascript - 在反应中将json保存在html li中
- eclipse-hono - 向 HTTP 协议适配器发送消息时,为什么会收到 HTTP/1.1 503 Service Unavailable?
- file-upload - HCL Domino AppDevPack - writeAttachments
- sql - PostgreSQL,从插入更新到 sql