-1

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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
shee
  • 165
  • 1
  • 10

2 Answers2

0

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
warownia1
  • 2,771
  • 1
  • 22
  • 30
-1

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)
  • cannot do that since 300-341 is a range so i stored them in tuple to check range conditions – shee Oct 22 '21 at 13:59
  • The answer is stated incorrectly: **tuples can be converted to JSON without issue**. The answer should specifically state that it applies to the case when tuples (or even lists) are used as keys in dictionaries. – rv.kvetch Oct 22 '21 at 14:04
  • Note also, that you're overriding the builtin type `dict` here. What happens when you do something like `dict()` in a following line? – rv.kvetch Oct 22 '21 at 14:07