1

我一直在寻找关于 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
4

2 回答 2

1

In fact Json needs as key a string. Is mandatory that they keys must be an integer? Just take this into account when you tray to deserialize the json an manage type conversion.

When deserializing: int(key) to get agin the integer. I supose is posible.

于 2013-07-05T11:03:48.157 回答
1

错误信息是正确的;根据JSON 标准,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))
于 2013-07-05T10:56:30.410 回答