由于JSON字符串字典键而导致数据丢失

编程入门 行业动态 更新时间:2024-10-25 10:30:45
本文介绍了由于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字符串字典键而导致数据丢失

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

发布评论

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

>www.elefans.com

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