I have some very simple code that takes a dictionary with a tuple as a key and turns it into json:
In [11]:
import simplejson as json
In [12]:
data = {('category1', 'category2'): 4}
In [13]:
json.dumps(data)
However, running the code gives me:
TypeError: keys must be a string
I have tried str()'ing the keys and everything else I can find, but without luck.
dumps() json. dumps() function converts a Python object into a json string. skipkeys:If skipkeys is true (default: False), then dict keys that are not of a basic type (str, int, float, bool, None) will be skipped instead of raising a TypeError.
The json. dumps() method allows us to convert a python object into an equivalent JSON object. Or in other words to send the data from python to json. The json. dump() method allows us to convert a python object into an equivalent JSON object and store the result into a JSON file at the working directory.
dumps() takes in a json object and returns a string.
json. dump() method used to write Python serialized object as JSON formatted data into a file. json. dumps() method is used to encodes any Python object into JSON formatted String.
The error seems pretty clear: Your keys must be strings.
If I take the example from your question and str()
-ify the keys:
>>> data = {str(('category1', 'category2')): 4}
It works just fine:
>>> json.dumps(data)
'{"(\'category1\', \'category2\')": 4}'
Having said that, in your position I would consider making your keys more readable. Possibly something like:
>>> data = dict((':'.join(k), v) for k,v in data.items())
This turns a key like ('category1', 'category2')
into category1:category2
,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With