Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 转储和重新加载的JSON与原始结构不匹配_Python_Json - Fatal编程技术网

Python 转储和重新加载的JSON与原始结构不匹配

Python 转储和重新加载的JSON与原始结构不匹配,python,json,Python,Json,MCVE(带py.试验) 我正在将一个json对象保存到磁盘,重新加载,发现它与原始对象不匹配。我怀疑unicode是有问题的,但是是什么导致了这个错误,以及最好的处理方法是什么 错误消息是: assert external == internal E assert {'0': ''} == {0: ''} E Left contains more items: E {u'0': u''} E R

MCVE(带py.试验)

我正在将一个json对象保存到磁盘,重新加载,发现它与原始对象不匹配。我怀疑unicode是有问题的,但是是什么导致了这个错误,以及最好的处理方法是什么

错误消息是:

    assert external == internal
E           assert {'0': ''} == {0: ''}
E             Left contains more items:
E             {u'0': u''}
E             Right contains more items:
E             {0: ''}
E             Use -v to get the full diff

在序列化为json时,整型键和浮点键隐式转换为字符串。这个简单的例子说明了这一点:

>json.dumps({1:2})
'{"1": 2}'
>>>json.dumps({'1':2})
'{"1": 2}'

显然,两个不同的Python对象被映射到同一个JSON,因此您无法始终将其来回转换。

在序列化为JSON时,整数和浮点键被隐式转换为字符串。这个简单的例子说明了这一点:

>json.dumps({1:2})
'{"1": 2}'
>>>json.dumps({'1':2})
'{"1": 2}'

显然,两个不同的Python对象被映射到同一个JSON,因此您不可能总是来回返回。在JSON中,所有键都是字符串,因此
JSON.dump
自动将数字转换为字符串。在JSON中,所有键都是字符串,因此
JSON.dump
自动将数字转换为字符串。
    assert external == internal
E           assert {'0': ''} == {0: ''}
E             Left contains more items:
E             {u'0': u''}
E             Right contains more items:
E             {0: ''}
E             Use -v to get the full diff