The catalogue team wanted a short blurb for every laptop in stock: four thousand SKUs, Dell, Lenovo and HP, each with a model name, CPU, RAM and price. That is a textbook batch job. You write one request per line into a file, upload it, and collect the results a few hours later at a lower price than live calls. The first upload was refused because the file was a JSON array saved as catalogue.json. The second one was accepted, then the batch failed validation with a list of line numbers. Every one of those errors came from a handful of mistakes that are easy to make and easy to check for.
This article covers the JSONL format itself, how batch and fine-tuning APIs use it, a checker you can run before you upload, and the errors behind messages like "must be .jsonl" and "line is not parseable as valid JSON".
What JSONL actually is
JSONL, also called JSON Lines or NDJSON, is a text file where every line is one complete JSON value. The JSON Lines spec is short, and it has three rules: the file is UTF-8 with no byte order mark, each line is a valid JSON value (a blank line is not), and lines end with \n. A \r\n ending also works, because the \r is just whitespace to a JSON parser.
That is the whole format. The point of it is that a reader never has to hold the whole file in memory: it can parse line 1, act on it, and move to line 2. It also means one bad line does not poison the rest, which is why batch APIs can tell you exactly which line failed.
The flip side is that a JSONL file is not one JSON document. Paste a whole .jsonl file into a JSON validator and it stops at line 2, column 1 with "There is more text after the end of the JSON value." That is correct behaviour, not a broken file. Validate one line at a time instead.
How the batch and fine-tuning APIs use it
The OpenAI Batch API takes a .jsonl file where each line is one request with a unique custom_id, a method, a url such as /v1/responses, and a body holding the normal request parameters. One file may target one model, and the current limits are 50,000 requests and 200 MB per file. The Files API also says plainly that batch and fine-tuning uploads only accept .jsonl files, which is where the "must be .jsonl" refusal comes from: rename the file and convert the content, both.
For supervised fine-tuning each line is one training example in chat format, and the file needs at least 10 lines. A helpdesk triage example looks like this, on a single line:
{"messages": [{"role": "system", "content": "You triage IT helpdesk tickets for laptops."}, {"role": "user", "content": "Serial 5CG4182QWX: battery drops from 80% to 0% in ten minutes."}, {"role": "assistant", "content": "Hardware fault. Book a battery replacement for HP EliteBook 840 G11, priority normal."}]}The Message Batches API from Anthropic works the other way round. You send the requests as a normal JSON body, a requests array of custom_id plus params, with up to 100,000 requests or 256 MB. The results come back as a .jsonl stream, one result per line. Its custom_id must match ^[a-zA-Z0-9_-]{1,64}$, so a SKU like HP EliteBook 840/G11 with spaces or a slash will not do. Both APIs warn that results may come back in a different order than you sent them; always match on custom_id.
Writing the file so it cannot be wrong
Nearly every bad JSONL file I have seen was written by gluing strings together. Let the JSON library write each line, and write the newline yourself:
import json
MODEL = "gpt-6-luna" # use a model your account can batch with
catalogue = [
{"sku": "DELL-LAT-7450", "brand": "Dell", "model": "Latitude 7450", "cpu": "Core Ultra 7 165U", "ram_gb": 16, "price": 1499.90},
{"sku": "LEN-T14-G5", "brand": "Lenovo", "model": "ThinkPad T14 Gen 5", "cpu": "Ryzen 7 PRO 8840U", "ram_gb": 32, "price": 1329.00},
{"sku": "HP-EB-840-G11", "brand": "HP", "model": "EliteBook 840 G11", "cpu": "Core Ultra 5 135U", "ram_gb": 16, "price": 1249.50},
]
with open("batch.jsonl", "w", encoding="utf-8", newline="\n") as f:
for item in catalogue:
request = {
"custom_id": item["sku"],
"method": "POST",
"url": "/v1/responses",
"body": {
"model": MODEL,
"input": "Write a two-sentence catalogue blurb for this laptop:\n" + json.dumps(item),
"max_output_tokens": 200,
},
}
# One object per line: no indent, and allow_nan=False so a NaN can never sneak in.
f.write(json.dumps(request, ensure_ascii=False, allow_nan=False) + "\n")
print(open("batch.jsonl", encoding="utf-8").read().count("\n"), "lines written")3 lines writtenThree details in that script do real work. json.dumps without indent keeps each request on one line and escapes the newline inside the prompt as \n. newline="\n" stops Windows from writing \r\n. And allow_nan=False matters more than it looks: by default Python's json module writes NaN and Infinity as bare words, which no JSON parser on the other end will accept. An empty price cell read with pandas becomes NaN, and json.dumps({"discount": float("nan")}) happily prints {"discount": NaN}.
If you already have a JSON array, jq converts it in one line, and back again:
# JSON array -> JSONL: one compact object per line
jq -c '.[]' catalogue.json > catalogue.jsonl
cat catalogue.jsonl
# JSONL -> JSON array, for tools that want one document
jq -s '.' catalogue.jsonl > roundtrip.json
jq length roundtrip.json{"sku":"DELL-LAT-7450","model":"Latitude 7450","ram_gb":16}
{"sku":"LEN-T14-G5","model":"ThinkPad T14 Gen 5","ram_gb":32}
{"sku":"HP-EB-840-G11","model":"EliteBook 840 G11","ram_gb":16}
3For a single record you have been editing by hand, the JSON minifier does the same job: paste the pretty-printed object, and the output is one line you can append to the file. It keeps every number exactly as written, so a 19-digit asset ID or a price of 1499.90 does not change on the way.
Check the file before you upload it
A batch that fails validation costs you a round trip. This checker reads the file the way a strict server does and reports problems by line number:
import json
import sys
def reject_constant(name):
# Python's json module accepts NaN and Infinity by default. JSON does not.
raise ValueError(f"{name} is not valid JSON")
def check(path):
raw = open(path, "rb").read()
problems = []
if raw.startswith(b"\xef\xbb\xbf"):
problems.append("line 1: file starts with a UTF-8 BOM")
raw = raw[3:]
text = raw.decode("utf-8")
lines = text.split("\n")
if lines and lines[-1] == "":
lines.pop() # a final newline is expected, not an empty record
seen = {}
for n, line in enumerate(lines, start=1):
line = line.rstrip("\r")
if not line.strip():
problems.append(f"line {n}: empty line")
continue
try:
obj = json.loads(line, parse_constant=reject_constant)
except ValueError as e:
problems.append(f"line {n}: not valid JSON ({e})")
continue
if not isinstance(obj, dict):
problems.append(f"line {n}: expected an object, got {type(obj).__name__}")
continue
cid = obj.get("custom_id")
if not isinstance(cid, str) or not cid:
problems.append(f"line {n}: missing custom_id")
elif cid in seen:
problems.append(f"line {n}: custom_id {cid!r} already used on line {seen[cid]}")
else:
seen[cid] = n
if not isinstance(obj.get("body"), dict):
problems.append(f"line {n}: body must be an object")
return len(lines), problems
count, problems = check(sys.argv[1])
print(f"{sys.argv[1]}: {count} lines, {len(problems)} problems")
for p in problems:
print(" " + p)To test it, I built a file with every mistake from the catalogue job: a BOM at the start, a comma left over from an array, a raw newline pasted into a string, a NaN from a spreadsheet, a blank line, and the same SKU twice.
import json
good = open("batch.jsonl", encoding="utf-8").read().splitlines()
broken = [
good[0],
good[1] + ",", # comma left over from an array
'{"custom_id": "HP-EB-840-G11", "body": {"input": "Weight: 1.4\nkg"}}', # raw newline inside a string
json.dumps({"custom_id": "HP-ZB-14-G1", "body": {"discount": float("nan")}}), # NaN from a spreadsheet
"", # blank line in the middle
good[0], # same custom_id twice
]
with open("broken.jsonl", "w", encoding="utf-8", newline="\n") as f:
f.write("" + "\n".join(broken) + "\n") # and a BOM, as Excel and Notepad like to add$ python3 check_jsonl.py batch.jsonl
batch.jsonl: 3 lines, 0 problems
$ python3 check_jsonl.py broken.jsonl
broken.jsonl: 7 lines, 7 problems
line 1: file starts with a UTF-8 BOM
line 2: not valid JSON (Extra data: line 1 column 347 (char 346))
line 3: not valid JSON (Unterminated string starting at: line 1 column 50 (char 49))
line 4: not valid JSON (Expecting value: line 1 column 1 (char 0))
line 5: not valid JSON (NaN is not valid JSON)
line 6: empty line
line 7: custom_id 'DELL-LAT-7450' already used on line 1Look at lines 3 and 4. One record with a raw line break inside a string turns into two broken lines, and the second one makes no sense on its own. When a batch error points at a line that looks like the tail end of a sentence, check the line above it.
Reading the error list a batch gives back
When the server finds a problem during validation, the batch object carries an errors list. Each entry has a code, a message and, where it applies, the line number in your input file. A message along the lines of "this line is not parseable as valid JSON" means exactly what the checker above prints: open the file, go to that line, and look for the problems in this list:
- A pretty-printed record. One object spread over twelve lines gives twelve broken lines. Write it with no indent.
- Array leftovers. A
[on the first line,]on the last, or commas at line ends: the file was a JSON array with the brackets half removed. - Raw newlines in strings. Text copied from an email or a PDF, glued in without escaping.
NaN,Infinity,Noneor single quotes. Signs that something printed a Python object withstr()instead ofjson.dumps().- A BOM or a UTF-16 file. Saved from Excel or an older Windows editor. Save as UTF-8 without BOM.
- A blank line. Usually two newlines between records, or one record that was deleted by hand.
Duplicate custom_id values are the other common refusal. They are not a JSON problem at all, but the checker catches them because they come from the same place: a script that was run twice and appended to the same file.
Sending the same requests to a JSON-body batch API
Because the Message Batches API wants a JSON body rather than an uploaded file, you can keep JSONL as your source format and convert at send time. The ID check runs first, since a bad ID refuses the whole batch:
import json
import re
CUSTOM_ID = re.compile(r"^[a-zA-Z0-9_-]{1,64}$")
requests = []
with open("batch.jsonl", encoding="utf-8") as f:
for n, line in enumerate(f, start=1):
req = json.loads(line)
if not CUSTOM_ID.match(req["custom_id"]):
raise SystemExit(f"line {n}: custom_id {req['custom_id']!r} has characters the API refuses")
requests.append({
"custom_id": req["custom_id"],
"params": {
"model": "claude-opus-5-5",
"max_tokens": 200,
"messages": [{"role": "user", "content": req["body"]["input"]}],
},
})
with open("anthropic-batch.json", "w", encoding="utf-8") as f:
json.dump({"requests": requests}, f, ensure_ascii=False)
print(len(requests), "requests,", len(open("anthropic-batch.json", "rb").read()), "bytes")
print(bool(CUSTOM_ID.match("HP EliteBook 840/G11")))3 requests, 1034 bytes
FalseUploading the OpenAI file is a single call to the Files API with the batch purpose:
curl https://api.openai.com/v1/files \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-F purpose="batch" \
-F file="@batch.jsonl"Reading results without loading the whole file
Results files can be hundreds of megabytes. Read them a line at a time and key everything by custom_id. This Node script reads a results file in the documented output shape, where one request has not come back yet:
import { createReadStream } from 'node:fs';
import { createInterface } from 'node:readline';
// Stream the file: a results file can be hundreds of MB, so never read it into one string.
const lines = createInterface({ input: createReadStream('results.jsonl'), crlfDelay: Infinity });
const blurbs = new Map();
let lineNo = 0;
for await (const line of lines) {
lineNo++;
if (!line.trim()) continue;
let row;
try {
row = JSON.parse(line);
} catch (err) {
console.error(`results.jsonl line ${lineNo}: ${err.message}`);
continue;
}
if (row.error) {
console.error(`${row.custom_id}: ${row.error.code}`);
continue;
}
const text = row.response.body.output[0].content[0].text;
blurbs.set(row.custom_id, text); // match by custom_id: output order is not input order
}
for (const sku of ['DELL-LAT-7450', 'LEN-T14-G5', 'HP-EB-840-G11']) {
console.log(sku.padEnd(14), blurbs.get(sku) ?? '(no result yet)');
}DELL-LAT-7450 A light 14-inch Latitude for people who travel.
LEN-T14-G5 A 14-inch business laptop with 32 GB of RAM.
HP-EB-840-G11 (no result yet)Failed requests in an OpenAI batch go to a separate error file, so a SKU with no blurb usually means "look in the error file", not "the job lost it". If you want to eyeball a results file first, copy a few lines and parse the JSON online one record at a time; the nested response.body.output structure is much easier to follow as a table than as one long line.
Wrapping up
- JSONL is one complete JSON value per line, UTF-8, no BOM, no blank lines. It is not one JSON document, so validate it line by line.
- Write lines with your JSON library and no indent. Never build them by joining strings.
- In Python, pass
allow_nan=Falseso aNaNfails on your machine instead of in the batch. - Run a checker before upload: parse each line, check for objects, and check that every
custom_idis unique and matches the API's pattern. - Match results by
custom_id, never by line order.
With a checker like this in the pipeline, a refused batch stops being a mystery. Most "invalid file" errors are a line number away from an answer.