简体   繁体   中英

Convert dictionary with tuples as keys to JSON

I want to convert a dictionary to a JSON object, but my key is a tuple, hence I am getting an issue when I do that:

import json

d = {(300, 341): 4, (342, 426): 5}
json.dumps(d)

Error:

TypeError: keys must be str, int, float, bool or None, not tuple

How can I solve this and access key elements if converted to JSON?

As the error states, tuples cannot be keys of JSON objects and you need some kind of a workaround. Consider serializing the tuples to strings, but converting them back to tuples might be a bit tricky in such case.

d = {str((300, 341)): 4, str((342, 426)): 5}
json.dumps(d)

Other option is to change the way you store your data to something like this

d = [
  {'key1': 300, 'key2': 341, 'value': 4},
  {'key1': 342, 'key2': 426, 'value': 5}
]

obviously you may change "key1" and "key2" to something more meaningful.

edit: As you mentioned you are working with ranges. How about this solution?

def jsonify_data(d):
  jsonifable = {'%d:%d' % key: val for key, val in d.items()}
  json.dumps(jsonifable)

def dejsonify_data(jd):
  d = {}
  for key, val in jd.items():
    start, end = key.split(':')
    d[int(start), int(end)] = val
  return d

You cannot convert a tuple to JSON directly, you would have to do it like this instead:

dict = {
  300: 4, 
  341: 4,
  342: 5,
  426: 5
}
json.dumps(dict)

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