DEV Community

James
James

Posted on • Originally published at ncot.uk on

1

Reading and Writing JSON using Python

JSON is a standard for storing data in a human readable format. It’s the modern world’s version of XML. Python comes with a JSON library that will parse the data and turn it into a regular Python dictionary. The library will also turn dictionaries into JSON data that can be written to a file.

Using this library is easy, these notes are mostly a reference for me, but you might find them useful too. The only thing to be aware of is the JSON library doesn’t do file handling, you need to do that yourself.

Reading Data

#!/usr/bin/env python3

import json

filename = "/path/to/file.json"

try:
    jsonFile = open(filename)
    jsonData = json.load(filename)
except:
    print ("Can't parse file", filename)
    exit(1)

After doing this, you can now treat jsonData as a regular Python dict, that matches the format of your JSON file. This means JSON arrays are arrays inside jsonData and JSON objects/associative arrays are Python dictionaries inside it.

If you print the jsonData variable out, and compare it to the JSON file, it’ll match up in sensible and logical ways.

Writing Data

This is pretty much the same, but the text needs manually writing to a file afterwards.

#!/usr/bin/env python3

import json

filename = "/path/to/file.json"

jsonData = dict()
# Fill the dict with data, as you would normally

try:
    outfile = open(filename,"w")
except:
    print ("Can't open output file", filename)
    exit(1)
jsonTest = json.dumps(jsonData, sort_keys=True, indent=4)
print(jsonTest, file=outfile)

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay