{ "cells": [ { "cell_type": "markdown", "id": "0961d098", "metadata": {}, "source": [ "# Data serialisation\n", "\n", "If the data is to be serialised flat, Python offers two functions:" ] }, { "cell_type": "markdown", "id": "fbb2b554", "metadata": {}, "source": [ "## `repr`\n", "\n", "[repr()](https://docs.python.org/3/library/functions.html#repr) outputs a printable representation of the input, for example:" ] }, { "cell_type": "code", "execution_count": 1, "id": "e42c5c0c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'id': 'veit', 'first_name': 'Veit', 'last_name': 'Schiele'}\n" ] } ], "source": [ "data = { \"id\" : \"veit\", \"first_name\": \"Veit\", \"last_name\": \"Schiele\" }\n", "\n", "print(repr(data))" ] }, { "cell_type": "code", "execution_count": 2, "id": "db1d7d73", "metadata": {}, "outputs": [], "source": [ "with open(\"data.txt\", \"w\") as f:\n", " f.write(repr(data))" ] }, { "cell_type": "markdown", "id": "051e66cd", "metadata": {}, "source": [ "## `ast.literal_eval`\n", "\n", "The [ast.literal_eval()](https://docs.python.org/3/library/ast.html#ast.literal_eval) function parses and analyses the Python data type of an expression. Supported data types are [strings](https://python-basics-tutorial.readthedocs.io/en/latest/types/strings.html), [numbers](https://python-basics-tutorial.readthedocs.io/en/latest/types/numbers.html), [tuples](https://python-basics-tutorial.readthedocs.io/en/latest/types/tuples.html), [lists](https://python-basics-tutorial.readthedocs.io/en/latest/types/lists.html), [dictionaries](https://python-basics-tutorial.readthedocs.io/en/latest/types/dicts.html) and [None](https://python-basics-tutorial.readthedocs.io/en/latest/types/none.html)." ] }, { "cell_type": "code", "execution_count": 3, "id": "2a81b27e", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'id': 'veit', 'first_name': 'Veit', 'last_name': 'Schiele'}\n" ] } ], "source": [ "import ast\n", "\n", "\n", "with open(\"data.txt\", \"r\") as f:\n", " d = ast.literal_eval(f.read())\n", " \n", "print(d)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3.11 Kernel", "language": "python", "name": "python311" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.5" }, "widgets": { "application/vnd.jupyter.widget-state+json": { "state": {}, "version_major": 2, "version_minor": 0 } } }, "nbformat": 4, "nbformat_minor": 5 }