Python 3home |
Introduction to Python
davidbpython.com
JavaScript Object Notation is a simple "data interchange" format for sending or storing structured data as text.
Fortunately for us, JSON resembles Python in many ways, making it easy to read and understand.
contents of file sample.json
{
"key1": ["a", "b", "c"],
"key2": {
"innerkey1": 5,
"innerkey2": "woah"
},
"key3": false,
"key4": null
}
The json.load() function decodes the contents of a JSON file.
import json # this module is used to read JSON files
fh = open('sample.json')
mys = json.load(fh) # load data objects from the file,
# convert into Python objects
fh.close()
print((type(mys))) # dict (the outer container of this struct)
print(mys['key2']['innerkey2']) # woah
Ex. 7.1
The json.loads() function decodes the contents of a JSON string.
import json # we use this module to read JSON
import requests # use 'pip install' to install
response = requests.get('https://davidbpython.com/mystruct.json')
text = response.text # str, entire file data
mys = json.loads(text) # read string, convert into Python container
print((type(mys))) # dict (the outer container of this struct)
print((mys['key2']['innerkey2'])) # woah
About requests:
A nested object can be confusing to read.
If we have an multidimensional object that is squished together and hard to read, we can use .dumps() with indent=4
import json
obj = {'a': {'x': 1, 'y': 2, 'z': 3}, 'b': {'x': 1, 'y': 2, 'z': 3}, 'c': {'x': 1, 'y': 2, 'z': 3} }
print((json.dumps(obj, indent=4)))
this prints:
{
"a": {
"x": 1,
"y": 2,
"z": 3
},
"b": {
"x": 1,
"y": 2,
"z": 3
}
}
We can use json.dump() to write to a JSON file.
import json
wfh = open('newfile.json', 'w') # open file for writing
obj = {'a': 1, 'b': 2}
json.dump(obj, wfh)
wfh.close()