JSON
Python - A Quick Start for existing Programers
1 min read
This section is 1 min read, full guide is 44 min read
Published Sep 16 2025, updated Sep 30 2025
21
Show sections list
0
Log in to enable the "Like" button
0
Guide comments
0
Log in to enable the "Save" button
Respond to this guide
Guide Sections
Guide Comments
Python
Python has a built in module called json for handling the conversion of json to Python objects and serialising Python objects to json.
It can be imported by:
import json
Copy to Clipboard
Converting between JSON and Python
There are the following methods:
- Serialise (Python → JSON string):
json.dumps(obj)→ Python object → JSON stringjson.dump(obj, file)→ write JSON directly to a file
- Deserialise (JSON string → Python):
json.loads(json_string)→ JSON string → Python objectjson.load(file)→ read JSON directly from a file
JSON ↔ Python type mappings:
JSON | Python |
Object | dict |
Array | list |
String | str |
Number | int/float |
true/false | True/False |
null | None |
Formatting options
indent=4→ pretty-print JSON with indentationsort_keys=True→ sort dictionary keys in outputseparators=(',', ': ')→ control formatting
Examples:
import json
# ----------------------------------------
# Python object
data = {
"name": "Alice",
"age": 30,
"is_admin": True,
"skills": ["Python", "Django", "Flask"],
"projects": None
}
# ----------------------------------------
# Python -> JSON string
json_string = json.dumps(data)
print("JSON string:", json_string)
# Pretty print JSON
pretty_json = json.dumps(data, indent=4, sort_keys=True)
print("Pretty JSON:\n", pretty_json)
# Write JSON to file
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
# ----------------------------------------
# JSON string -> Python
parsed = json.loads(json_string)
print("Parsed back to Python:", parsed)
print("Name:", parsed["name"])
# Read JSON from file
with open("data.json", "r") as f:
from_file = json.load(f)
print("From file:", from_file)
# ----------------------------------------
# Controlling separators (compact JSON)
compact_json = json.dumps(data, separators=(',', ':'))
print("Compact JSON:", compact_json)
Copy to Clipboard
Toggle show comments














