gpt4 book ai didi

python - 如何在 Python 中使用 JSONDecoder?只获取内部字典进行解码

转载 作者:太空宇宙 更新时间:2023-11-03 11:08:52 26 4
gpt4 key购买 nike

我有一个 JSONEncoder 和 JSONDecoder:

class SimpleTargetJSONEncoder(json.JSONEncoder):
"""
converts a SimpleTarget to a Dict so it can be JSONified
"""

def default(self, o):
if isinstance(o, SimpleTargetItem):
return {
'x': o.x(),
'y': o.y(),
'status': o.status,
'imageSet': o.imageSet}


class SimpleTargetJSONDecoder(json.JSONDecoder):
def __init__(self):
json.JSONDecoder.__init__(self, object_hook=self.dict_to_object)

def dict_to_object(self, d):
t = SimpleTargetItem(imageSet=d['imageSet'])
t.setX(d['x'])
t.setY(d['y'])
return t

编码器写出这样的文件:

[
{
"y": 2514.0,
"x": 2399.0,
"status": "default",
"imageSet": {
"default": ":/images/blue-circle.png",
"active": ":/images/green-circle.png",
"removed": ":/images/black-circle.png",
}
},
{
"y": 2360.0,
"x": 2404.0,
"status": "default",
"imageSet": {
"default": ":/images/blue-square.png",
"active": ":/images/green-square.png",
"removed": ":/images/black-square.png",
}
}
]

但是当我调用解码器时,我得到:

/Library/Frameworks/Python.framework/Versions/2.7/bin/python /Users/dmd/Documents/inmotion/py/targetlayoutdesigner/designer.py
Traceback (most recent call last):
File "/Users/dmd/Documents/inmotion/py/targetlayoutdesigner/targetlayoutwindow.py", line 131, in loadLayout
for t in SimpleTargetJSONDecoder().decode(open(fname).read()):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
obj, end = self.scan_once(s, idx)
File "/Users/dmd/Documents/inmotion/py/targetlayoutdesigner/targetitem.py", line 113, in dict_to_object
t = SimpleTargetItem(imageSet=d['imageSet'])
KeyError: 'imageSet'

如果那时我看 d,d 就是这样:

{u'active': u':/images/green-circle.png',
u'default': u':/images/blue-circle.png',
u'removed': u':/images/black-circle.png'}

即内部字典。

我做错了什么?

最佳答案

您假设您只会获得所需的字典,而不是所有 字典。

class SimpleTargetJSONDecoder(json.JSONDecoder):
def __init__(self):
json.JSONDecoder.__init__(self, object_hook=self.dict_to_object)

def dict_to_object(self, d):
if 'x' not in d or 'y' not in d:
return d
t = SimpleTargetItem(imageSet=d['imageSet'])
t.setX(d['x'])
t.setY(d['y'])
return t

关于python - 如何在 Python 中使用 JSONDecoder?只获取内部字典进行解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11507983/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com