考虑以下示例
>>> 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字符串字典键而导致数据丢失
发布评论