rope.base.serializer

This module serves to convert a data structure composed of Python primitives (dict, list, tuple, int, str, None) to JSON-serializable primitives (object, array, number, str, null).

A core feature of this serializer is that the produced will round-trip to identical objects when deserialized by the standard library json module. In other words, this property always holds:

>>> original_data = ... any JSON ...
>>> encoded = python_to_json(original_data)
>>> serialized = json.dumps(encoded)
>>> decoded = json.loads(serialized)
>>> rehydrated_data = json_to_python(decoded)
>>> assert rehydrated_data == original_data
>>> assert encoded == decoded

Couple challenges in straight serialization that this module helps resolve:

  • json.dumps() maps both Python list and tuple to JSON array. This module provides two variants:

    • In version=1, this module converts Python list [1, 2, 3] as-is and converts Python tuple (1, 2, 3) to special object construct {“$”: “t”, “items”: [1, 2, 3]}

    • In version=2, it is the other way around, this module converts Python tuple (1, 2, 3) as-is and converts Python list [1, 2, 3] to special object construct {“$”: “l”, “items”: [1, 2, 3]}

  • Python dict keys can be a tuple/dict, but JSON Object keys must be strings This module replaces all dict keys with refid which can be resolved using the encoded[“references”][refid] lookup table. Except there’s a small optimisation, if the dict key is a string that isn’t only numeric, which is encoded directly into the object.

  • Python dict keys cannot be another dict because it is unhashable, therefore there’s no encoding for having objects as keys either.

  • There is currently no support for floating point numbers.

Note that json_to_python only accepts Python objects that can be the output of python_to_json, there is NO guarantee for going the other way around. This may or may not work:

>>> python_to_json(json_to_python(original_data)) == original_data

Functions

python_to_json(o[, version])

json_to_python(o)

Module Contents

rope.base.serializer.python_to_json(o, version=1)
rope.base.serializer.json_to_python(o)