Using Python to parse JSON
Parse JSON
Deserialization
Use json.loads() to parse a JSON string to a Python dictionary.
Use json.load() to parse a JSON file to a Python dictionary.
Serialization
Use json.dumps() to convert a Python dictionary to a JSON string.
Pass the indent parameter into json.dumps() to format the string.
Use json.dump() to convert a Python dictionary to a JSON file.
Example:
import json #import the Python built-in json module
with open('books.json') as myfile:
pyDict = json.load(myfile) #parse json
print(json.dumps(pyDict, indent=4))
Update JSON File
Example:
import json
with open('booktitle.json') as fileObj: # Create Python object from JSON file.
pyDict = json.load(fileObj)
pyDict.update({"publication_date": 2020}) #update value.
jsonFormattedStr = json.dumps(jsonObj, indent=2)
print(jsonFormattedStr)
Example:
import json
with open('booktitle.json') as fileObj: # Create Python object from JSON file.
pyDict = json.load(fileObj)
pyDict["binding"] = "paperback" #add new key and value.
jsonFormattedStr = json.dumps(jsonObj, indent=2)
print(jsonFormattedStr)
Example:
with open('bookslist.json') as fileObj: # Create Python object from JSON file.
pyList = json.load(fileObj) #json array converted to Python list.
pyList[2]['booktitle'] = 'Watership down' # Update 3rd key and value.
pyList[2]['author'] = 'Adams, Richard'
pyList[2]['publisher'] = 'Scribner'
pyList[2]['publication_date'] = 2005
jsonFormattedStr = json.dumps(jsonObj, indent=2)
print(jsonFormattedStr)