Data serialisation¶
If the data is to be serialised flat, Python offers two functions:
repr
¶
repr() outputs a printable representation of the input, for example:
[1]:
data = { "id" : "veit", "first_name": "Veit", "last_name": "Schiele" }
print(repr(data))
{'id': 'veit', 'first_name': 'Veit', 'last_name': 'Schiele'}
[2]:
with open("data.txt", "w") as f:
f.write(repr(data))
ast.literal_eval
¶
The ast.literal_eval() function parses and analyses the Python data type of an expression. Supported data types are strings, numbers, tuples, lists, dictionaries and None.
[3]:
import ast
with open("data.txt", "r") as f:
d = ast.literal_eval(f.read())
print(d)
{'id': 'veit', 'first_name': 'Veit', 'last_name': 'Schiele'}