GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Books
  • Mini
  • Tips
  • Tags
  • About
  • learnbyexample
  • Python tip 20: saving and loading json

This view

  • Original page
  • New address

GeezerVison is showing learnbyexample.github.io — 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}

info See docs.python: json for documentation, more examples, other methods, caveats and so on.

Video demo:


info See also my 100 Page Python Intro ebook.

#python#tip

← Python tip 21: sorting iterables based on a key

Python tip 19: manipulating string case →


📰 Use this link for the Atom feed.
✅ Follow me on Twitter, GitHub and Youtube for interesting tech nuggets.


You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.