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)
Top comments (0)