JSON¶
JSON is the format every social media API returns.
This notebook reads and writes JSON with Python's json module, then covers the problems that come up with real data: text encoding, speed, broken files, validation, files too large for memory, and compression.
Sections: Load JSON, Dump JSON, Encoding, Faster JSON libraries, Broken JSON, Validate with Pydantic, JSONL, Compression.
Packages beyond the standard library: ujson, json_repair, pydantic.
Install them with uv add ujson json-repair pydantic (or pip install).
# The sample files live next to this notebook in data/. In Colab they do not
# exist yet, so this cell downloads them from the course repository.
import pathlib
import urllib.request
base_url = "https://raw.githubusercontent.com/YangKCLab/social-media-analysis/main/docs/topics/data-format-management/data/"
pathlib.Path("data").mkdir(exist_ok=True)
for name in ["sample.json", "sample_broken.json"]:
path = pathlib.Path("data") / name
if not path.exists():
urllib.request.urlretrieve(base_url + name, path)
print(sorted(p.name for p in pathlib.Path("data").iterdir()))
import json
Load JSON¶
data/sample.json is a small hand-written file with every JSON type in it: strings, numbers, booleans, null, an array, and nested objects.
Open it in a text editor first. JSON is plain text.
print(open("data/sample.json").read())
json.load() reads from an open file and returns Python objects: a JSON object becomes a dict, an array becomes a list, null becomes None, and true/false become True/False.
with open("data/sample.json") as f:
sample_obj = json.load(f)
type(sample_obj)
sample_obj
json.loads() (with an s, for string) parses a string that is already in memory.
API client libraries usually hand you a string or an already-parsed object; loads is for the string case.
with open("data/sample.json") as f:
file_content = f.read()
sample_obj = json.loads(file_content)
sample_obj["name"]
Nested values are reached one key at a time. Arrays are indexed by position.
print(sample_obj["address"]["city"])
print(sample_obj["address"]["coordinates"]["latitude"])
print(sample_obj["hobbies"][0])
Real API responses do not always contain every field.
A 4chan post has a com key only when the post has text, and a Bluesky post has an embed key only when something is attached.
obj["key"] raises KeyError when the key is absent; obj.get("key") returns None instead, and obj.get("key", default) returns a default of your choice.
print(sample_obj.get("spouse"))
print(sample_obj.get("nickname"))
print(sample_obj.get("nickname", "no nickname on record"))
Dump JSON¶
json.dumps() turns Python objects back into a JSON string.
Without arguments it produces one long line, which is what you want in a file that another program will read.
json.dumps(sample_obj)
indent=2 produces the human-readable form. Use it when a person will look at the file, not for data files: the indentation costs space and buys nothing for a parser.
print(json.dumps(sample_obj, indent=2))
json.dump() (no s) writes straight to an open file.
with open("data/write_sample.json", "w") as f:
json.dump(sample_obj, f, indent=2)
print(open("data/write_sample.json").read()[:120])
Encoding¶
Social media text contains emoji, accented letters, and non-Latin scripts. A file is bytes, and an encoding is the rule that maps text to bytes. UTF-8 is the encoding that every API and every modern tool uses. Use it everywhere and most encoding problems never appear.
By default json.dumps() escapes every non-ASCII character as \uXXXX. The result is valid JSON that any parser reads back correctly, but a person cannot read it.
encoding_obj = {"japanese": "でたらめ", "chinese": "你好", "emoji": "🐍"}
json.dumps(encoding_obj)
ensure_ascii=False keeps the characters as they are. The string then contains non-ASCII text, so the file must be opened with encoding="utf-8" when you write it.
json.dumps(encoding_obj, ensure_ascii=False)
with open("data/encoding_obj.json", "w", encoding="utf-8") as f:
json.dump(encoding_obj, f, ensure_ascii=False)
with open("data/encoding_obj.json", encoding="utf-8") as f:
print(json.load(f))
What goes wrong when encodings do not match: write the file as UTF-16, then read it with the default (UTF-8).
The bytes of the wrong encoding cannot be decoded, so Python raises UnicodeDecodeError before json even sees the text.
with open("data/encoding_obj_utf16.json", "w", encoding="utf-16") as f:
json.dump(encoding_obj, f, ensure_ascii=False)
try:
with open("data/encoding_obj_utf16.json", encoding="utf-8") as f:
json.load(f)
except UnicodeDecodeError as e:
print("UnicodeDecodeError:", e)
Reading it with the encoding it was written in works. You rarely get to choose the encoding of a file someone else made, so when a file fails to decode, the first question is which encoding produced it.
with open("data/encoding_obj_utf16.json", encoding="utf-16") as f:
print(json.load(f))
import timeit
import ujson
records = [{"id": i, "text": "post number %d" % i, "likes": i % 7, "tags": ["a", "b"]} for i in range(100_000)]
text = json.dumps(records)
t_json = timeit.timeit(lambda: json.loads(text), number=3) / 3
t_ujson = timeit.timeit(lambda: ujson.loads(text), number=3) / 3
print(f"json.loads: {t_json:.3f} s for {len(records):,} records")
print(f"ujson.loads: {t_ujson:.3f} s for {len(records):,} records")
Broken JSON¶
data/sample_broken.json looks like the sample file but has two mistakes on lines 2 and 4: single quotes around a string, and False with a capital F.
Both are legal in Python and illegal in JSON.
print(open("data/sample_broken.json").read()[:80])
with open("data/sample_broken.json") as f:
file_content = f.read()
try:
json.loads(file_content)
except json.JSONDecodeError as e:
print("JSONDecodeError:", e)
The error names the line and column, which is enough to fix a file by hand.
For files you cannot fix by hand, or for text produced by a language model that was asked for JSON, json_repair guesses the intended structure and returns valid JSON.
It is a guess: check the result before trusting it.
from json_repair import repair_json
repaired_json = repair_json(file_content)
repaired_obj = json.loads(repaired_json)
repaired_obj["name"], repaired_obj["isStudent"]
Validate with Pydantic¶
Valid JSON is not the same as correct data. A record can parse and still have a missing field, a string where a number should be, or a list that arrived as a single value. Pydantic checks a parsed object against a model you write as a Python class. Use it at the boundaries of your pipeline: data from an API, data from a user, data from a language model.
from typing import Optional
from pydantic import BaseModel, ValidationError
class User(BaseModel):
id: int
name: str
age: Optional[int] = None
tags: list[str] = []
raw_data = {"id": 42, "name": "Alice", "tags": ["admin", "tester"]}
User.model_validate(raw_data)
model_validate_json takes the JSON string directly, so parsing and checking happen in one call.
User.model_validate_json(json.dumps(raw_data))
When the data does not fit the model, ValidationError says which field and why.
bad_data = {"id": 42, "name": "Alice", "tags": "admin"}
try:
User.model_validate(bad_data)
except ValidationError as e:
print(e)
A model for a social media post looks the same. Nested objects become nested models, and Pydantic converts an ISO 8601 timestamp string into a datetime.
from datetime import datetime
class Author(BaseModel):
did: str
handle: str
class Post(BaseModel):
uri: str
text: str
created_at: datetime
author: Author
like_count: int = 0
post = Post.model_validate({
"uri": "at://did:plc:abc/app.bsky.feed.post/3k2",
"text": "hello",
"created_at": "2025-08-26T04:36:32.229Z",
"author": {"did": "did:plc:abc", "handle": "example.bsky.social"},
})
post.created_at, post.author.handle
JSONL¶
A collector that runs for weeks produces millions of records. Stored as one JSON array, the whole file must be parsed before the first record is available, and the whole array must fit in memory. A 100 GB JSON array does not load on a machine with 32 GB of RAM.
JSON Lines (JSONL, extension .jsonl) stores one JSON value per line.
Each line is parsed on its own, so a file of any size can be read one record at a time, and a collector can append a record by writing one line.
Every data-collection notebook on this site writes JSONL.
list_of_objs = [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "John"},
{"id": 3, "name": "Joe"},
]
with open("data/list_of_objs.jsonl", "w") as f:
for obj in list_of_objs:
f.write(json.dumps(obj) + "\n")
print(open("data/list_of_objs.jsonl").read())
obj_list = []
with open("data/list_of_objs.jsonl") as f:
for line in f:
obj_list.append(json.loads(line))
obj_list
Two rules keep a JSONL file usable:
- One record per line, and nothing else. Never pretty-print into a JSONL file.
- Open the file in append mode (
"a") from a collector, and flush after each round. If the process dies, every line written so far is intact. The file is a log.
with open("data/list_of_objs.jsonl", "a") as f:
f.write(json.dumps({"id": 4, "name": "Ana"}) + "\n")
with open("data/list_of_objs.jsonl") as f:
print(sum(1 for _ in f), "lines")
Compression¶
JSON is text, and text compresses well: field names repeat on every line.
gzip is the usual choice because every tool reads it, and Python's gzip.open() works like open().
Write with mode "wt" (text) and read with "rt"; the encoding is UTF-8 by default.
import gzip
with gzip.open("data/list_of_objs.jsonl.gz", "wt", encoding="utf-8") as f:
for obj in list_of_objs:
f.write(json.dumps(obj) + "\n")
with gzip.open("data/list_of_objs.jsonl.gz", "rt", encoding="utf-8") as f:
for line in f:
print(json.loads(line))
How much it saves, on the 100,000 synthetic records from the timing section:
import os
with open("data/records.jsonl", "w") as f:
for r in records:
f.write(json.dumps(r) + "\n")
with gzip.open("data/records.jsonl.gz", "wt", encoding="utf-8") as f:
for r in records:
f.write(json.dumps(r) + "\n")
plain = os.path.getsize("data/records.jsonl")
packed = os.path.getsize("data/records.jsonl.gz")
print(f"records.jsonl: {plain / 1e6:.1f} MB")
print(f"records.jsonl.gz: {packed / 1e6:.1f} MB ({plain / packed:.0f}x smaller)")
Real posts compress less than these synthetic records, because the text differs from line to line, but a factor of 5 to 10 is typical. Compress files once they are complete; do not compress the file a collector is still appending to.
# Clean up the files this notebook created.
for name in ["write_sample.json", "encoding_obj.json", "encoding_obj_utf16.json",
"list_of_objs.jsonl", "list_of_objs.jsonl.gz", "records.jsonl", "records.jsonl.gz"]:
pathlib.Path("data", name).unlink(missing_ok=True)