Official Doc: https://docs.python.org/3/library/json.html
Import the JSON module:
json_example.py
import json
Convert Python Object to JSON
json_example.py
>>> import json
>>> colors = ["red","green","blue"]
>>> colors_in_json = json.dumps(colors)
>>> colors_in_json
# ["red","green","blue"]
Parse JSON object
json_example.py
>>> import json
>>> capitals_in_json = [{"country":"Vietnam","capital":"Hanoi"},{"country":"France","capital":"Paris"}]
>>> capitals = json.loads(capitals_in_json)
>>> capitals
# [{"country":"Vietnam","capital":"Hanoi"},{"country":"France","capital":"Paris"}]
Write to .json file
json_example.py
import json
colors = ["red","green","blue"]
with open("colors.json","w") as file:
json.dump(colors)
Read from .json file
json_example.py
import json
with open("colors.json") as file:
colors = json.load(colors)
print(colors)
# ["red","green","blue"]