Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json.dump() gives me "TypeError: keys must be a string"

Tags:

python

json

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.

like image 206
Anton Avatar asked Jun 03 '15 19:06

Anton


People also ask

Does JSON dump string?

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.

What is JSON dump ()?

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.

What is the return type of JSON dumps?

dumps() takes in a json object and returns a string.

What is the difference between JSON dumps and JSON dump?

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.


1 Answers

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,

like image 194
larsks Avatar answered Oct 23 '22 13:10

larsks