Code for How to Work with JSON Files in Python Tutorial


View on Github

saving_json.py

import json

# example dictionary to save as JSON
data = {
    "first_name": "John",
    "last_name": "Doe",
    "email": "[email protected]",
    "salary": 1499.9, # just to demonstrate we can use floats as well
    "age": 17,
    "is_real": False, # also booleans!
    "titles": ["The Unknown", "Anonymous"] # also lists!
}

# save JSON file
# 1st option
with open("data1.json", "w") as f:
    json.dump(data, f)

# 2nd option
with open("data2.json", "w") as f:
    f.write(json.dumps(data, indent=4))


unicode_data = {
    "first_name": "أحمد",
    "last_name": "علي"
}

with open("data_unicode.json", "w", encoding="utf-8") as f:
    json.dump(unicode_data, f, ensure_ascii=False)

loading_json.py

import json

# read a JSON file
# 1st option
file_name = "data1.json"
with open(file_name) as f:
    data = json.load(f)
    
print(data)
# 2nd option
file_name = "data2.json"
with open(file_name) as f:
    data = json.loads(f.read())

print(data)

example.py (pip3 install requests)

import requests
import json


# make API request and parse JSON automatically
data = requests.get("https://jsonplaceholder.typicode.com/users").json()
# save all data in a single JSON file
file_name = "user_data.json"
with open(file_name, "w") as f:
    json.dump(data, f, indent=4)
    print(file_name, "saved successfully!")

# or you can save each entry into a file
for user in data:
    # iterate over `data` list
    file_name = f"user_{user['id']}.json"
    with open(file_name, "w") as f:
        json.dump(user, f, indent=4)
        print(file_name, "saved successfully!")


# load 2nd user for instance
file_name = "user_2.json"
with open(file_name) as f:
    user_data = json.load(f)
    
print(user_data)
print("Username:", user_data["username"])