Why JSON is Preferred
Compared to alternatives (XML, YAML, CSV, TXT, custom formats), JSON often wins because:
- Human-readable & lightweight: Uses clear key-value syntax, easy to inspect.
- Language-agnostic: Supported in almost every programming language with built-in or library support.
- Widely adopted in web APIs: Many web services accept/request JSON payloads.
- Flexible structure: Can represent nested data easily vs CSV which is flat.
Writing JSON in Python
- JSON supports various data types including strings, lists, tuples, integers, floats, booleans, and more. When serialized and later deserialized, the original Python data types are preserved.
Using json.dump
import json
from pathlib import Path
path = Path("test.json") # json filename
content = {
"name": "Alice",
"age": 30,
"languages": ["Python", "JavaScript"],
"active": True,
}
with open(path,"w") as file_name:
json.dump(content,file_name)
Using json.dumps
import json
from pathlib import Path
path = Path("test.json") # json filename
content = {
"name": "Alice",
"age": 30,
"languages": ["Python", "JavaScript"],
"active": True,
}
json_format= json.dumps(content) # convert python format in json string
path.write_text(json_format) # write the json string into json file
Differences: dump
vs dumps
dump
: writes directly to a file object; no intermediate string held in memory (good for large data).dumps
: returns JSON string; useful when you need the JSON text for other uses (e.g., HTTP body, logging).
Reading JSON in Python
Python’s json
module provides:
json.load(file_obj)
: parse JSON content from an open file objectfile_obj
into Python objects.json.loads(json_string)
: parse JSON from a string into Python objects.
Using json.load
Read JSON directly from a file:
import json
from pathlib import Path
path=Path("test.json")
with open(path, "r", encoding="utf-8") as f: # encoding="utf-8" read effectively
loaded = json.load(f)
print(loaded)
# Example output:
# {'name': 'Alice', 'age': 30, 'languages': ['Python', 'JavaScript'], ...}
Using json.loads
Parse JSON from a string:
import json
from pathlib import Path
data=path.read_text() # read the json string text
content=json.loads(data) # convert json string iin python readable
print(content)
# Example output: {'name': 'Bob', 'age': 25, 'active': False}
Differences: load
vs loads
load
: reads and parses directly from a file-like object; convenient for file operations.loads
: parses from a string; use when JSON is already in-memory (e.g., response.text).
Code in Action
Create a small example to demonstrate write/read cycle:
import json
import os
# Example data
config = {
"app_name": "MyApp",
"version": "1.0.0",
"features": {"enable_feature_x": True, "max_items": 100},
"users": ["alice", "bob", "charlie"]
}
# 1. Write JSON to file
file_path = "config.json"
with open(file_path, "w", encoding="utf-8") as f:
json.dump(config, f, indent=2)
print(f"Written JSON to {file_path}")
# 2. Read JSON back
with open(file_path, "r", encoding="utf-8") as f:
loaded_config = json.load(f)
print("Loaded config:", loaded_config)
# 3. Modify and re-serialize using dumps
loaded_config["version"] = "1.1.0"
json_str = json.dumps(loaded_config)
print("Modified JSON string:", json_str)
# 4. Parse from JSON string
parsed = json.loads(json_str)
print("Parsed back to Python dict:", parsed)
Running this will:
- Write a
config.json
file with pretty-printed JSON. - Read it back into a Python dict.
- Modify the dict, serialize to string via
dumps
, and display. - Parse the JSON string back via
loads
to verify consistency.
Conclusion
JSON file handling in Python is straightforward with the built-in json
module. Remember:
- Use
json.dump
to write to files,json.dumps
to get a string. - Use
json.load
to read from files,json.loads
to parse strings. - Specify
encoding="utf-8"
, handle exceptions, and choose pretty-printing as needed.
With these patterns and tips, you can reliably read/write JSON for configs, data interchange, and more.
Tags
#Python #json #filehandling #dump #dumps #load #loads #codingtips #developer