Syntax
import jsonExamples
Converting Python to JSON
Serializing a Python dictionary into a JSON-formatted string.
import json
data = {
"name": "John",
"age": 21,
"skills": ["Python", "TypeScript", "React"]
}
json_string = json.dumps(data)
print(json_string)
# {"name": "John", "age": 21, "skills": ["Python", "TypeScript", "React"]}
pretty = json.dumps(data, indent=2)
print(pretty) # nicely formatted with indentationParsing JSON
Converting a JSON string back into native Python objects.
import json
json_string = '{"name": "Zain", "age": 22, "active": true}'
data = json.loads(json_string)
print(data["name"]) # Zain
print(type(data)) # <class 'dict'>
print(data["active"]) # True (JSON true becomes Python True)Reading and Writing JSON Files
Working with JSON data stored in files directly.
import json
data = {"project": "DevNexus", "version": "1.0"}
with open("config.json", "w") as f:
json.dump(data, f, indent=2)
with open("config.json", "r") as f:
loaded = json.load(f)
print(loaded)Handling Invalid JSON
Gracefully catching errors when parsing malformed JSON.
import json
bad_json = "{name: John}" # missing quotes around keys - invalid JSON
try:
data = json.loads(bad_json)
except json.JSONDecodeError as e:
print(f"Invalid JSON: {e}")Best practices
- Use json.dump()/json.load() when working directly with files, and json.dumps()/json.loads() when working with strings already in memory
- Wrap json.loads() in a try/except for json.JSONDecodeError when parsing data from an external or untrusted source
- Use the indent parameter with json.dumps() to produce human-readable output for config files or debugging
- Remember not every Python object is JSON-serializable by default (like datetime or custom classes) - convert them to strings or use a custom encoder first
Runtime & versions
Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Python language reference