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

编程入门 行业动态 更新时间:2024-10-22 20:25:43
本文介绍了如何在Python中使用JSONDecoder?仅获取内部字典进行解码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个JSONEncoder和JSONDecoder:

I have a JSONEncoder and 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

编码器写出这样的文件:

The encoder writes out a file like this:

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

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

But when I call the decoder, I get:

/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就是这样:

And if I look at d at that point, d is just this:

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

即内部命令.

我在做什么错了?

推荐答案

您假设您只会得到想要的字典,而不是所有的 字典.

You're assuming that you'll get only the dict you want, instead of all dicts.

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中使用JSONDecoder?仅获取内部字典进行解码

本文发布于:2023-11-26 18:00:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634604.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   如何在   Python   JSONDecoder

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!