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)

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more