Skip to content

Idea/Discussion - Applying a similar technique to dictionaries and their keys? #87

@aggieNick02

Description

@aggieNick02

One common lesson-learned for a python dev using json.dumps followed by json.loads is that json requires string keys, so numeric keys become strings after a serialize/deserialize cycle.

It's interesting to think about applying the same technique pyjson_tricks uses to support so many data types to dictionaries and their keys. A python dict could become a special json dict with __dict__ magic key, along with an entry for an array of arrays for the key/value pairs. Then the dictionary keys would be able to survive a serialize/deserialize cycle with their type intact.

For example, right now we have this behavior:

>>> a={1:2,3:4}
>>> json_tricks.dumps(a)
'{"1": 2, "3": 4}'
>>> json_tricks.loads(json_tricks.dumps(a))
OrderedDict([('1', 2), ('3', 4)])

Instead we could have this, with keys preserved:

>>> a={1:2,3:4}
>>> json_tricks.dumps(a)
'{"__dict__":None, keys_and_values:[[1, 2],[3, 4]]'
>>> json_tricks.loads(json_tricks.dumps(a))
OrderedDict([(1, 2),(3,4)])

pyjson_tricks lets you do a non-destructive dumps/loads cycle on a much larger set of types than regular json while avoiding the security and readability drawbacks of pickle. Having it be able to do that for dictionaries with non-string keys would increase that set of types significantly.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions