Home > other >  Convert dictionary with tuples as keys to JSON
Convert dictionary with tuples as keys to JSON

Time:10-23

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?

CodePudding user response:

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

CodePudding user response:

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)
  • Related