我已经找到了关于SO的答案,但没有答案特别有用。我有一个值的字典,我必须转换为JSON字符串。数据如下所示:
In [127]: ddd
Out[127]:
{'ID': {'condition': '',
'data': {1: '2',
2: '3',
3: '4',
4: '5',
5: '6',
6: '7',
7: '8',
8: '9',
9: '10'},
'desc_long': 'Id szko\xc5\x82y',
'desc_short': 'Id szko\xc5\x82y',
'df_name': 'pierszytest',
}}
当我尝试执行json.dumps(ddd)时,我得到:
TypeError: keys must be a string
我创建了一个测试变量“what”
In [126]: what
Out[126]: {1: '2', 2: '3', 3: '4', 4: '5', 5: '6', 6: '7', 7: '8', 8: '9', 9: '10'}
json.dumps(what)返回:
Out[129]: '{"1": "2", "2": "3", "3": "4", "4": "5", "5": "6", "6": "7", "7": "8", "8": "9", "9": "10"}'
同样,我试图仅转换ddd ['ID'] ['data']:
In [131]: ddd['ID']['data']
Out[131]: {1: '2', 2: '3', 3: '4', 4: '5', 5: '6', 6: '7', 7: '8', 8: '9', 9: '10'}
In [130]: json.dumps(ddd['ID']['data'])
TypeError: keys must be a string
所以,这基本上是相同的变量,仍然json.dumps无法处理后者。这对我来说是一个很大的惊喜。我做了一些研究,但它对我的案子没有任何用处。如果它是重复的,请告诉我。
*编辑* 我在两个变量上附加了type()的结果:
In [132]: type(ddd['ID']['data'])
Out[132]: dict
In [133]: type(what)
Out[133]: dict
答案 0 :(得分:1)
错误信息正确无误;根据{{3}}:
,JSON对象中的键必须是字符串object = begin-object [ member *( value-separator member ) ]
end-object
member = string name-separator value
因此,要么选择除JSON之外的其他格式,要么让您的键成为字符串。在您的情况下,您希望将numpy.int64
变量转换为字符串;尝试以下方法:
# This paragraph is just for testing, replace it with your actual code
import pandas as pd
import numpy as np
d = pd.Series([1,3,5,np.nan,6,8]).to_dict()
ddd = {'ID': {'DATA': d}}
import json
import copy
def _convert(dct):
return dict((str(k),v) for k, v in dct.items())
ddd_json = copy.deepcopy(ddd)
ddd_json['ID']['data'] = _convert(ddd_json['ID']['data'])
print(json.dumps(ddd_json, indent=2))
答案 1 :(得分:1)
实际上Json需要一个字符串作为键。必须是它们的键必须是整数吗?在托盘将json反序列化为管理类型转换时,请考虑这一点。
反序列化时: int(key)获取整数的agin。我觉得可行。