JSON and JSONL (JSON Lines) are related text data formats, but they are structured and processed differently depending on whether you need a single document or a stream of individual records.
Standard JSON requires a single valid document enclosed in an object (
{}) or array ([]), with all items separated by commas.JSONL files contain one valid JSON object per line, separated by \n. This format lets you append new records easily and stream massive datasets line by line without loading the entire file into memory.
JSON requires loading and parsing the entire file into memory at once. JSONL can be read line-by-line, meaning memory consumption stays low regardless of file size.
# Working with Standard JSON
# json.dump() writes it directly to an open file, while json.load() reads a file.
# json.dumps() and json.loads(). Use these functions (with an s for string) to convert between Python objects and JSON-formatted strings.
import json
data = {
"user": "Alice",
"roles": ["admin", "editor"],
"active": True
}
# Writing standard JSON to a file
with open("config.json", mode="w", encoding="utf-8") as file:
json.dump(data, file, indent=4)
# Reading standard JSON from a file
with open("config.json", mode="r", encoding="utf-8") as file:
loaded_data = json.load(file)
print(loaded_data["user"]) # Output: Alice# Working with JSONL (JSON Lines)
import json
records = [
{"id": 1, "event": "login"},
{"id": 2, "event": "purchase"},
{"id": 3, "event": "logout"}
]
# Writing JSONL (one JSON string per line)
with open("events.jsonl", mode="w", encoding="utf-8") as file:
for record in records:
file.write(json.dumps(record) + "\n")
# Reading JSONL line by line (memory-efficient)
with open("events.jsonl", mode="r", encoding="utf-8") as file:
for line in file:
if line.strip(): # Skip empty lines
event = json.loads(line)
print(event["id"], event["event"])