Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 5 · Concept · 15 min · revision 2

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

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.

Parsing one JSON object
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 None

JSON has two gaps to plan for:

  • No date or time type. Store timestamps as ISO 8601 strings such as 2024-05-02T09:15:00Z and convert them when you read. json.dumps raises TypeError on a datetime.
  • No NaN. Python's json module writes NaN by default, which is not valid JSON, so stricter parsers reject the file. Pass allow_nan=False to fail at write time instead, and store a missing number as null.
NaN is accepted by default, rejected with allow_nan=False
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: nan

JSON 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.

Writing and reading JSON Lines
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
tickets.jsonl
{"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.

The csv module handles quotes, commas and line breaks
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)  # True
sample.csv as written
ticket_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 the csv module. 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.

Writing Parquet, then reading back two columns
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)
Output (pandas 3.1.1, pyarrow 26.0.1)
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:00

The 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ïve becomes naï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 with errors='ignore', which silently deletes whatever it cannot decode.
Characters, bytes and a wrong 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ïve

The 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.

The same file read as 'utf-8' and as 'utf-8-sig'
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

Practice check · 3 questions

Formats and encodings

Answer from what you saw in this lesson. Each question has one best answer.

Q1. A spreadsheet export loads with `csv.DictReader`, but `row['ticket_id']` raises `KeyError`. Printing the keys shows `'\ufeffticket_id'` first. What should you change?
Q2. Which option gives a reader `account_id` as the text `'004217'` and `created_at` as a timestamp, with no type hints in the reading code?
Q3. A batch job records one result per processed document and may crash halfway. You want earlier results kept, and a damaged write should affect one record at most. Which format fits best?
Practice only: not graded, not saved, not evidence.

07. Apply it

Pick one data source your project reads and write a short file contract for it:

  1. The format, and why it was chosen.
  2. The encoding. If open(path, 'rb').read(3) returns b'\xef\xbb\xbf', the file starts with a BOM.
  3. 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.
  4. 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.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check