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?
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.
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.
JSON only allows key names to be strings. Those strings can consist of numerical values.
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.
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.
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