Python

Parse JSON in Python

Learn how to parse and create JSON in Python using the json module with loads(), dumps(), and file operations.

Try JSON Formatter →

Code Example

import json

# Parse JSON string
json_string = '{"name": "John", "age": 30}'
data = json.loads(json_string)
print(data['name'])  # John

# Convert dict to JSON string
user = {"name": "Jane", "age": 25}
json_str = json.dumps(user)
print(json_str)  # {"name": "Jane", "age": 25}

# Pretty print JSON
pretty = json.dumps(user, indent=2)
print(pretty)

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

# Write JSON to file
with open('output.json', 'w') as f:
    json.dump(user, f, indent=2)

# Handle errors
try:
    data = json.loads(invalid_json)
except json.JSONDecodeError as e:
    print(f"Invalid JSON: {e}")
Key Points: Python's json module provides loads()/dumps() for strings and load()/dump() for files. Use indent parameter for pretty printing.

Related Examples

More Python Examples