Files - json
Just like with yaml files, json files store dictionaries. They are common not only in Python, but many other languages as well, such as JavaScript and HTML. The format of the file is more strict than yaml; where yaml didn't require quotation marks to indicate strings and used indentation to demark dictionary levels, json requires double quotes (single quotes won't work either) surrounding keys, as well as the use of curly brackets. Let's see what a json file might look like.
{
"SP 500": {
"Y2022": {
"average": 4097,
"high": 4796,
"low": 3577
},
"Y2021": {
"average": 4273,
"high": 4793,
"low": 3700
}
}
}
the json package is built into python, so we can import it without any
trouble. We need a file context to read or write json, just like with
yaml. Let's see how to read this file into memory with the function
json.load
. Once we've read the file into memory, we should
close the file context, as good practice.
import json
f = open("./data.json", "r")
stock_index = json.load(f)
f.close()
print(stock_index["SP 500"]["Y2022"])
> {'average': 4097, 'high': 4796, 'low': 3577}
print(stock_index["SP 500"]["Y2021"]["average"])
> 4723
Now how may we write a dictionary to memory? With the function
json.dump
stock_index = {
"SP 500": {
"yearly avgs": [4097, 4273],
"yearly highs": [4796, 4793]
}
}
f = open("data.json", "w")
json.dump(stock_index, f, indent=4)
f.close()
If we were to open the file we would see the following content.
{
"SP 500": {
"yearly avgs": [
4097,
4273
],
"yearly highs": [
4796,
4793
]
}
}
The parameters start with the dictionary to dump, then the file to write to.
The parameter indent=4
helps pretty print the file so that it's
easier to read.