简体   繁体   中英

In Python json.dumps fails to process dictionary of { integer : 'string' ,}

I have looked for an answer on SO, however no answer was particulary useful. I have a dictionary of values that I have to convert to JSON string. The data looks like this:

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',
}}

When I try to execute json.dumps(ddd) I get :

TypeError: keys must be a string

I created a test variable "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) returns:

Out[129]: '{"1": "2", "2": "3", "3": "4", "4": "5", "5": "6", "6": "7", "7": "8", "8": "9", "9": "10"}'

Again, I tried to convert only 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

So, this are basically the same variables and still json.dumps fails to deal with the latter. This is a big surpise for me. I have done some research, but it returned nothing useful for my case. If it's a duplicate, please let me know.

* EDIT * I attach result of type() on both variables:

In [132]: type(ddd['ID']['data'])
Out[132]: dict

In [133]: type(what)
Out[133]: dict

The error message is correct; keys in JSON objects must be strings, according to the JSON standard :

object = begin-object [ member *( value-separator member ) ]
         end-object
member = string name-separator value

Therefore, either choose another format than JSON, or let your keys be strings. In your case, you want to convert numpy.int64 variables to strings; try the following:

# 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))

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM