Python tip 20: saving and loading json
JSON (JavaScript Object Notation) is one of the ways you can store and retrieve data necessary for functioning of an application. For example, my projects Python regex exercises and Linux CLI text processing exercises need to load questions and save user progress. You might wonder why not just a plain text file? I needed dict
in the code anyway and JSON offered seamless transition. Also, this arrangement avoided having to write extra code and test it for potential parsing issues.
The json
builtin module is handy for such purposes. Here's an example of saving a dict
object:
>>> import json
>>> marks = {'Rahul': 86, 'Ravi': 92, 'Rohit': 75, 'Rajan': 79}
>>> with open('marks.json', 'w') as f:
... json.dump(marks, f, indent=4)
...
In the above example, indent
is used for pretty printing. Here's how the file looks like:
$ cat marks.json
{
"Rahul": 86,
"Ravi": 92,
"Rohit": 75,
"Rajan": 79
}
And here's an example of loading a JSON file:
>>> with open('marks.json') as f:
... marks = json.load(f)
...
>>> marks
{'Rahul': 86, 'Ravi': 92, 'Rohit': 75, 'Rajan': 79}
See docs.python: json for documentation, more examples, other methods, caveats and so on.
Video demo:
See also my 100 Page Python Intro ebook.