How to read and write JSON in Python

How to read JSON in Python from a file

import json

# Read JSON from a file
with open('data.json') as f:
    data = json.load(f)

# Print the data
print(data)

How to write JSON in Python to a file

import json

# Create a dictionary
data = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

# Write JSON to a file
with open('data.json', 'w') as f:
    json.dump(data, f)

How to read JSON in Python from a string

import json

# Read JSON from a string
data = json.loads('{"name": "John", "age": 30, "city": "New York"}')

# Print the data
print(data)

How to write JSON in Python to a string

import json

# Create a dictionary
data = {
    'name': 'John',
    'age': 30,
    'city': 'New York'
}

# Write JSON to a string
json_string = json.dumps(data)

# Print the JSON string
print(json_string)

# indentation
json_string = json.dumps(data, indent=4)

# Print the indented JSON string
print(json_string)

Where to go next: