A .jsonl file (note the "L" at the end, which stands for "Lines") is a text file format where each line is a separate JSON object. Unlike a traditional JSON file, which contains a single, coherent JSON structure (like an array or object), a JSONL file has one JSON object per line, making it easier to:
- Append new data: Just add a new line with the new JSON object.
- Stream large datasets: Read or write line-by-line without loading the entire file into memory.
- Process in parallel: Different lines (JSON objects) can be processed independently.
Here's an example of what a .jsonl file looks like:
{"name": "Alice", "age": 30, "city": "New York"}
{"name": "Bob", "age": 25, "city": "Los Angeles"}
{"name": "Charlie", "age": 35, "job": "Engineer"}
Notice:
- Each line is a valid JSON object.
- There's no comma separation between lines.
- No wrapping
[ ] or { } structure around the whole file.
Now, let's see how to read a .jsonl file in Python.
Method 1: Simple Line-by-Line Reading
You can use the built-in json module. Just open the file, iterate over lines, and parse each line as JSON:
import json
file_path = 'data.jsonl'
with open(file_path, 'r') as file:
for line in file:
try:
json_obj = json.loads(line)
print(json_obj) # Do something with the JSON object
except json.JSONDecodeError as e:
print(f"Error decoding JSON: {e}")
Here's what's happening:
open(file_path, 'r'): Opens the file in read mode.
for line in file: Iterates line-by-line (memory-efficient).
json.loads(line): Parses the line into a Python dictionary (or list, if your JSON object is an array).
try-except: Catches malformed JSON lines (optional but recommended).
Example output:
{'name': 'Alice', 'age': 30, 'city': 'New York'}
{'name': 'Bob', 'age': 25, 'city': 'Los Angeles'}
{'name': 'Charlie', 'age': 35, 'job': 'Engineer'}
Method 2: Load All Lines into a List
If your file fits in memory, you can load all JSON objects into a list:
import json
with open(file_path, 'r') as file:
data = [json.loads(line) for line in file]
print(data)
# Output:
# [
# {'name': 'Alice', 'age': 30, 'city': 'New York'},
# {'name': 'Bob', 'age': 25, 'city': 'Los Angeles'},
# {'name': 'Charlie', 'age': 35, 'job': 'Engineer'}
# ]
This is equivalent to:
data = []
with open(file_path, 'r') as file:
for line in file:
data.append(json.loads(line))
Method 3: Using pandas (for tabular data)
If your JSONL data is mostly uniform (e.g., same keys in each object), pandas is super handy:
import pandas as pd
df = pd.read_json(file_path, lines=True)
print(df)
Output:
name age city job
0 Alice 30 New York NaN
1 Bob 25 Los Angeles NaN
2 Charlie 35 NaN Engineer
The lines=True argument tells pandas to expect JSONL format. Now you have a DataFrame, ready for analysis!
Writing a .jsonl File
Just for completeness, here's how to write data to a .jsonl file:
import json
data = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35}
]
with open('output.jsonl', 'w') as file:
for obj in data:
json.dump(obj, file)
file.write('\n') # Critical: add newline after each JSON object
Alternatively, a one-liner:
with open('output.jsonl', 'w') as file:
for obj in data:
file.write(json.dumps(obj) + '\n')
Key Points
- Memory-efficient: Read line-by-line unless you need all data in memory.
- Uniform data? Use
pandas.read_json(..., lines=True).
- Error handling: Wrap
json.loads() in try-except for robustness.
- Writing:
json.dump(obj, file) + file.write('\n').
Now you're all set to work with .jsonl files in Python! 🚀
Bonus tip: Tools like jq (command-line JSON processor) also support JSONL natively:
jq -c '.name' data.jsonl # Outputs: "Alice" \n "Bob" \n "Charlie"