Reputation: 17247
The JSON equivalent of a Python dict is a JSON object. However its keys must be strings, that's a well-known limitation.
I need to support also boolean and numeric keys. I could make a simple Python value <--> JSON string one-to-one translation:
False <--> "bool:False"
42 <--> "int:42"
"Foo" <--> "str:Foo"
But I'd like to ask if there is some existing recommendation or some kind of standard for this. Simply anything that it is worth to be compatible with.
Upvotes: 2
Views: 2238
Reputation: 140168
Since you cannot issue standard JSON, why don't you just use str
to serialize and ast.literal_eval
(standard package) to deserialize?
>>> d = {'a': 33, 23:(4,5), False: 10, 4: "foo"}
>>> a = str(d) # convert the python structure to a string
>>> d2 = ast.literal_eval(a)
>>> print(d2) # evaluate the a literal to a python structure
{False: 10, 4: 'foo', 'a': 33, 23: (4, 5)}
>>> d2 == d # are those the same before & after evaluation ?
True
Upvotes: 0
Reputation: 298146
JSON isn't able to do that and I don't know of any widely-used extensions of JSON that allow you to do this. You'd have to write the serializer and deserializer yourself, which probably wouldn't be that difficult if you subclass json.JSONEncoder
and json.JSONDecoder
.
If you're able to switch protocols, there are JSON-ish protocols that support non-string keys. MessagePack is one:
>>> import msgpack
>>> msgpack.loads(msgpack.dumps({'1': 12, False: 3, 2: 8}))
{False: 3, 2: 8, '1': 12}
Upvotes: 1
Reputation: 2881
This would achieve what you want:
>>> import json
>>> data = {False: 'this data', 42: 'answer', 'foo': 'bar'}
>>> json.dumps({"%s:%s" % (type(k).__name__, k): v for k, v in data.items()})
'{"int:42": "answer", "str:foo": "bar", "bool:False": "this data"}'
You'd then have to de-serialize this, and it would only work for basic types.
Upvotes: 0