由于JSON字符串字典键而导致数据丢失 [英] Data loss due to json stringifying dict keys

查看:159
本文介绍了由于JSON字符串字典键而导致数据丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下示例

>>> import json
>>> d = {0: 'potato', '0': 'spud'}
>>> json.dumps(d)
'{"0": "potato", "0": "spud"}'
>>> json.loads(json.dumps(d))
{'0': 'spud'}

我希望为此引发例外.在文档中,对于反序列化器有一些关于object_pairs_hook kwarg的知识,但是最好早点在序列化器中失败,而不要首先生成奇怪的json"输出.

I'd prefer for this to raise exception. In the docs there is a bit about object_pairs_hook kwarg for the deserialiser, but it would be better to fail early at the serialiser and not generate the "weird json" output in the first place.

json内置的文件中有什么可以帮助我的,或者替换上的任何降低对dict更为谨慎?我宁愿不必扩展JSONEncoder并尽可能检查每个dict键.

Is there anything in the json builtin to help me, or any drop in replacement which is a bit more cautious with dicts? I'd rather not have to extend JSONEncoder and pre-check every dict key if possible.

推荐答案

实际上,如果您使用Python的json模块,则没有任何出路(因为您说过,您不希望对键进行任何预检查或自定义).但是,如果事情将保留在Python中,则可以尝试使用demjson库,因为它似乎可以某种方式处理integer \ string问题.不过,我自己还没有尝试过.

Actually, if you stay with Python's json module, there's no way out (as you said you don't want any pre-checks of keys or customizing). But if things are going to stay inside Python, you can try the demjson library, for it seems to handle integer\string problem somehow. I haven't tried it myself, although.

这篇关于由于JSON字符串字典键而导致数据丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆