JSON, CSV, Parquet and Text Encodings
Learn what JSON, JSON Lines, CSV and Parquet each store and forget, and how to read and write text files without encoding damage.
Contentsand lesson path
On this page
- Why it matters
- JSON and JSON Lines
- CSV: a text table without types
- Parquet: typed, columnar and binary
- Text encodings: bytes on disk, text in Python
- Check your understanding
- Apply it
- Review prompt
Lessons of Data Handling
- JSON, CSV, Parquet and Text Encodings Concept · 15 min
- Round-Tripping Records Safely, CSV Versus Parquet Worked example · 20 min
- Schema Validation with Pydantic Models Lab · 25 min
- Tabular Cleaning with pandas Lab · 25 min
- Check: Clean a Messy Dataset Knowledge check · 6 questions
What you will learn
- Parse JSON and CSV into Python structures and serialize results back without losing data or encoding.
Prerequisites: Python Foundations
01. Why it matters
Most AI-engineering work starts with files someone else produced: helpdesk exports, scraped pages, model logs, evaluation sets. Your code has to parse them into Python structures before anything reaches a chunker or an embedding model, and later write results back out.
That boundary is where quiet damage happens. A CSV export turns the account id 004217 into 4217. The word naïve arrives as naïve. A ticket body containing a comma splits across two columns. None of this raises an error; it flows into the corpus and surfaces weeks later as poor retrieval or garbled answers.
For each of JSON, JSON Lines, CSV and Parquet, and for the text encoding underneath them, learn what it stores, what it forgets, and which arguments you must pass to read and write it faithfully.
02. JSON and JSON Lines
JSON maps neatly onto Python: objects become dict, arrays list, strings str, whole numbers int, other numbers float, true and false become True and False, and null becomes None. json.loads and json.dumps convert strings; json.load and json.dump work on open files.
import json
raw = '{"ticket_id": 1042, "language": "vi", "priority": null, "tags": ["login"]}'
record = json.loads(raw)
print(record)
# {'ticket_id': 1042, 'language': 'vi', 'priority': None, 'tags': ['login']}
print(type(record["ticket_id"]).__name__, record["priority"]) # int NoneJSON has two gaps to plan for:
- No date or time type. Store timestamps as ISO 8601 strings such as
2024-05-02T09:15:00Zand convert them when you read.json.dumpsraisesTypeErroron adatetime. - No NaN. Python's
jsonmodule writesNaNby default, which is not valid JSON, so stricter parsers reject the file. Passallow_nan=Falseto fail at write time instead, and store a missing number asnull.
import json
print(json.dumps({"score": float("nan")})) # {"score": NaN}, not valid JSON
json.dumps({"score": float("nan")}, allow_nan=False)
# ValueError: Out of range float values are not JSON compliant: nanJSON Lines (JSONL) stores one complete JSON value per line. It is the usual format for evaluation sets, fine-tuning data, batch requests and logs, because you can append a record without rewriting the file, stream a large file line by line, and a corrupt line breaks only that record. A line break inside a string is written as the escape \n, so a multi-line ticket still occupies one line.
import json
tickets = [
{"ticket_id": 1042, "language": "vi", "text": "Không đăng nhập được"},
{"ticket_id": 1043, "language": "fr", "text": "Facture en double"},
]
with open("tickets.jsonl", "w", encoding="utf-8") as f:
for ticket in tickets:
print(json.dumps(ticket, ensure_ascii=False), file=f)
with open("tickets.jsonl", encoding="utf-8") as f:
loaded = [json.loads(line) for line in f if line.strip()]
print(loaded == tickets) # True{"ticket_id": 1042, "language": "vi", "text": "Không đăng nhập được"}
{"ticket_id": 1043, "language": "fr", "text": "Facture en double"}ensure_ascii=False writes Không as readable characters instead of \u escapes. Both forms load back to the same string; the readable one just needs the file opened as UTF-8.
03. CSV: a text table without types
A CSV file is a plain-text table: a header line, then one record per line, with fields separated by commas. Every spreadsheet opens it, which is why tools export it, and it gives you the fewest guarantees of the four formats.
The first trap is quoting. A field containing a comma, a double quote or a line break is wrapped in double quotes, and quotes inside it are doubled. Splitting lines on commas breaks on real data; use the csv module or pandas.read_csv, which apply the rules for you.
import csv
rows = [
{"ticket_id": "1042", "text": 'Error "E42", then logged out'},
{"ticket_id": "1043", "text": "Line one\nLine two"},
]
with open("sample.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["ticket_id", "text"])
writer.writeheader()
writer.writerows(rows)
with open("sample.csv", encoding="utf-8", newline="") as f:
print(list(csv.DictReader(f)) == rows) # Trueticket_id,text
1042,"Error ""E42"", then logged out"
1043,"Line one
Line two"Pass two arguments every time you open a CSV file:
newline=''leaves line endings to thecsvmodule. Without it, line breaks inside quoted fields may be misread, and on Windows each written row gains an extra\r.encoding='utf-8'(or'utf-8-sig'for reading, explained below). Without it, Python before 3.15 uses the platform's locale encoding, which differs between machines; Python 3.15 defaults to UTF-8 (PEP 686), but naming the encoding keeps the code correct on every version.
The second trap is that CSV has no types. The csv module returns every value as a str, and a missing value and an empty string are both just an empty field. Readers that guess types, such as pandas, decide for you: 004217 becomes 4217, timestamps stay strings, and an empty field becomes NaN. The next lesson shows each case.
04. Parquet: typed, columnar and binary
Apache Parquet is a binary format for analytical tables. It differs from the text formats in two ways:
- It stores a schema. Every column has a declared type (64-bit integer, string, timestamp with time zone and so on) and can hold nulls, so leading zeros, timestamps and missing values come back exactly as written.
- It stores data column by column, so a reader can load only the columns it needs and skip the rest, such as a long text column that a count or a join does not use.
The costs: it is not human-readable, you cannot append rows the way you append lines to JSON Lines, and you need a library. pandas reads and writes Parquet through pyarrow, installed with pip install pandas pyarrow.
import pandas as pd
df = pd.DataFrame(
{
"ticket_id": [1042, 1043],
"account_id": ["004217", "000981"],
"created_at": pd.to_datetime(["2024-05-02T09:15:00Z", "2024-05-03T14:40:00Z"]),
"text": ["Không đăng nhập được", "Facture en double"],
}
)
df.to_parquet("tickets.parquet", index=False) # needs pyarrow installed
subset = pd.read_parquet("tickets.parquet", columns=["account_id", "created_at"])
print(subset.dtypes)
print(subset)account_id str
created_at datetime64[us, UTC]
dtype: object
account_id created_at
0 004217 2024-05-02 09:15:00+00:00
1 000981 2024-05-03 14:40:00+00:00The zeros and the UTC zone came back with no hints in the reading code. str is the text dtype, and datetime64[us, UTC] a timestamp stored to the microsecond in UTC. (pandas 2.x prints object for text columns and datetime64[ns, UTC] for timestamps; the values are the same.)
A rough rule for choosing:
- JSON Lines for records passed between services, logs, and datasets that grow by appending.
- CSV when a person or a spreadsheet must open the file, with a written note of each column's type.
- Parquet for tables you will reread, filter, join and aggregate, especially large ones.
05. Text encodings: bytes on disk, text in Python
A file holds bytes; a Python str holds Unicode characters. An encoding converts between them, and UTF-8, which stores ASCII in one byte and everything else in two to four, is the standard choice. When the reader assumes a different encoding from the writer, one of two things happens:
- Mojibake. UTF-8 bytes decoded as cp1252 or Latin-1 turn each accented character into two or three wrong ones, with no error. That is how
naïvebecomesnaïve. - A decode error. Decoding cp1252 or Latin-1 bytes as UTF-8 usually raises
UnicodeDecodeError. That is the better outcome, because you find out at once. Do not hide it witherrors='ignore', which silently deletes whatever it cannot decode.
text = "Hà Nội, naïve"
print(len(text), len(text.encode("utf-8"))) # 13 17
print("naïve".encode("utf-8").decode("cp1252")) # naïveThe byte order mark (BOM) has a confusing symptom. Some Windows tools, including Excel's CSV UTF-8 export, start the file with the bytes EF BB BF. Decoding as 'utf-8' keeps them as an invisible \ufeff glued to the first column name, so row['ticket_id'] raises KeyError although the header looks right.
'utf-8-sig' removes a BOM when there is one and changes nothing otherwise, so use it to read CSV files from unknown sources. Write plain 'utf-8' unless the file is meant to be opened in Excel.
import csv
with open("export.csv", "w", encoding="utf-8-sig", newline="") as f:
f.write("ticket_id,language\r\n1042,vi\r\n")
with open("export.csv", encoding="utf-8", newline="") as f:
print(next(csv.reader(f))) # ['\ufeffticket_id', 'language']
with open("export.csv", encoding="utf-8-sig", newline="") as f:
print(next(csv.reader(f))) # ['ticket_id', 'language']06. Check your understanding
07. Apply it
Pick one data source your project reads and write a short file contract for it:
- The format, and why it was chosen.
- The encoding. If
open(path, 'rb').read(3)returnsb'\xef\xbb\xbf', the file starts with a BOM. - Every field that holds an id with leading zeros, a date or time (and its time zone), or a value that can be missing, and how missing is written.
- The exact
open()or pandas call your code uses to read it.
The schema-validation lab later in this skill turns a contract like this into checks that run on every row.
08. Review prompt
Without scrolling up, name one thing that JSON, CSV and Parquet each cannot store or cannot do. Then explain why, before Python 3.15, leaving out the encoding= argument can make the same script read a file correctly on one machine and garble it on another.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.