Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do int keys of a python dict turn into strings when using json.dumps?

According to this conversion table, Python ints get written as JSON numbers when serialized using the JSON module--as I would expect and desire.

I have a dictionary with an integer key and integer value:

>>> d = {1:2} >>> type(d.items()[0][0]) <type 'int'> >>> type(d.items()[0][1]) <type 'int'> 

When I use the json module to serialize this to a JSON string, the value is written as a number, but the key is written as a string:

>>> json.dumps(d) '{"1": 2}' 

This isn't the behavior I want, and it seems particularly broken since it breaks json.dumps/json.loads round-tripping:

>>> d == json.loads(json.dumps(d)) False 

Why does this happen, and is there a way I can force the key to be written as a number?

like image 252
jveldridge Avatar asked Jun 14 '13 00:06

jveldridge


People also ask

Why are JSON keys strings?

The JSON format is deliberately based on a subset of JavaScript object literal syntax and array literal syntax, and JavaScript objects can only have strings as keys - thus JSON keys are strings too.

Does JSON dumps convert to string?

dumps() is for converting to JSON, not from JSON to string. str has absolutely nothing to do with JSON; the fact that str(somedict) looks sort of like JSON is coincidence.

Can integers be keys in JSON?

JSON only allows key names to be strings. Those strings can consist of numerical values.

Is JSON key always string?

In JSON, the “keys” must always be strings. Each of these pairs is conventionally referred to as a “property”. In Python, "objects" are analogous to the dict type. An important difference, however, is that while Python dictionaries may use anything hashable as a key, in JSON all the keys must be strings.


1 Answers

The simple reason is that JSON does not allow integer keys.

object     {}     { members }  members     pair     pair , members pair     string : value  # Keys *must* be strings. 

As to how to get around this limitation - you will first need to ensure that the receiving implementation can handle the technically-invalid JSON. Then you can either replace all of the quote marks or use a custom serializer.

like image 136
Sean Vieira Avatar answered Sep 24 '22 23:09

Sean Vieira