Registry / serialization / ndjson

ndjson

JSON →
library0.3.1pypypi✓ verified 23d ago

The `ndjson` library for Python, currently at version `0.3.1`, provides a `JsonDecoder` and `JsonEncoder` for newline-delimited JSON (NDJSON), also known as JSON Lines. It offers a familiar interface similar to Python's built-in `json` module, enabling efficient reading and writing of NDJSON data to and from file-like objects and strings. This lightweight library has no external dependencies and is particularly useful for processing large datasets or streaming applications where each line represents a complete, independent JSON object. Although its last release was in 2020 and its PyPI status is 'Pre-Alpha', it is considered stable and functional for its stated purpose.

pip install ndjson
INSTALL
IMPORT
SIG · NDJSON
N
ndjson
serializationpythonv0.3.1
Install
1.6s avg
Import
10ms
Disk
16MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.3.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.010s · 17.8MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.6s · import 0.006s · 18MB
16MB installed
● package 16MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

ndjson
import ndjson
load
ndjson.load(file_object)
dump
ndjson.dump(data, file_object)
loads
ndjson.loads(string_data)
dumps
ndjson.dumps(data)
reader
ndjson.reader(file_object)
writer
ndjson.writer(file_object)

This quickstart demonstrates how to write and read NDJSON data using the `ndjson` library's `dump`/`load` functions for bulk operations and `writer`/`reader` classes for streaming line-by-line processing, similar to Python's `csv` module. This is particularly efficient for large files, avoiding the need to load the entire dataset into memory.

import ndjson import os # Example data data_to_write = [ {"name": "Alice", "age": 30, "city": "New York"}, {"name": "Bob", "age": 24, "city": "San Francisco"}, {"name": "Charlie", "age": 35, "city": "London"} ] file_path = "example.ndjson" # --- Writing NDJSON to a file --- with open(file_path, 'w', encoding='utf-8') as f: # Using ndjson.dump for a list of objects ndjson.dump(data_to_write, f) print(f"Data written to {file_path} using ndjson.dump") # Alternatively, using ndjson.writer for streaming individual rows file_path_writer = "example_writer.ndjson" with open(file_path_writer, 'w', encoding='utf-8') as f: writer = ndjson.writer(f) for record in data_to_write: writer.writerow(record) print(f"Data written to {file_path_writer} using ndjson.writer") # --- Reading NDJSON from a file --- read_data_dump = [] with open(file_path, 'r', encoding='utf-8') as f: # Using ndjson.load for reading all objects from a file read_data_dump = ndjson.load(f) print(f"\nData read from {file_path} (ndjson.load):\n{read_data_dump}") # Alternatively, using ndjson.reader for streaming individual rows read_data_reader = [] with open(file_path_writer, 'r', encoding='utf-8') as f: reader = ndjson.reader(f) for row in reader: read_data_reader.append(row) print(f"\nData read from {file_path_writer} (ndjson.reader):\n{read_data_reader}") # Clean up created files os.remove(file_path) os.remove(file_path_writer)
Debug
Known issues
gotchaThe `ndjson` library's official PyPI status is "2 - Pre-Alpha", which might suggest instability or an experimental nature. However, the library has been stable since its 0.3.1 release in February 2020 and "works as advertised", making this status misleading for its current functional state.
fix
Be aware of the PyPI status, but understand that the library is stable for its intended use cases. The version 0.3.1 has been consistent since 2020.
affects: 0.1.0 - 0.3.1
gotchaDo not attempt to parse an entire NDJSON file using Python's built-in `json.load()` (e.g., `json.load(open('data.ndjson'))`). This will typically result in a `json.JSONDecodeError` because NDJSON files contain multiple top-level JSON objects, not a single one, or a `MemoryError` for very large files.
fix
Use `ndjson.load(file_object)` or iterate with `ndjson.reader(file_object)` for stream-based parsing, which correctly handles newline-delimited JSON objects.
affects: All versions (general Python usage)
gotchaWhen writing NDJSON, ensure each record is a valid, self-contained JSON object on a single line, terminated by a newline character (`\n`). Do not wrap the entire set of objects in a JSON array (`[]`) or add commas between objects, as this violates the NDJSON format and will cause parsing issues.
fix
The `ndjson` library handles this correctly with `ndjson.dump()` and `ndjson.writer()`. When manually constructing NDJSON, always ensure one valid JSON object per line.
affects: All versions (general NDJSON format adherence)
deprecatedThe library's last release (`0.3.1`) was in February 2020. While its core functionality is stable and complete for handling NDJSON, users seeking active development, bug fixes beyond the existing scope, or new features might find the project inactive.
fix
Evaluate if the current feature set meets your needs. For very large-scale or high-performance NDJSON processing, consider alternatives like `ijson` for incremental parsing or `orjson` for faster JSON operations, or libraries integrated with dataframes like `polars.read_ndjson`.
affects: 0.3.1 and earlier
gotchaNDJSON files are expected to be UTF-8 encoded. Parsing issues can occur with files saved with a Byte Order Mark (BOM) or mixed encodings. This is a common issue for many text-based file formats.
fix
Always specify `encoding='utf-8'` when opening NDJSON files. If a BOM is present and causing issues, use `encoding='utf-8-sig'` to automatically strip it.
affects: All versions (general file handling)
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'ndjson'
The 'ndjson' library has not been installed in the current Python environment.
fix
pip install ndjson
Process finished with exit code 137 (interrupted by signal 9: SIGKILL)
Attempting to load a large NDJSON file using Python's standard `json.load()` method, which tries to read the entire file into memory as a single JSON object, exceeding available RAM.
fix
Use `ndjson.load()` for file-like objects, or iterate through the file line by line, parsing each line as a separate JSON object using `ndjson.loads()`:

```python
import ndjson

# Using ndjson.load() for file-like objects
with open('data.ndjson', 'r', encoding='utf-8') as f:
    data = ndjson.load(f)

# Or for very large files, process line by line
def read_ndjson_lines(filepath):
    with open(filepath, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if line: # Skip empty lines
                yield ndjson.loads(line)

for record in read_ndjson_lines('data.ndjson'):
    print(record)
```
json.JSONDecodeError: Expecting value:
An individual line within the NDJSON file is not a valid JSON object, containing syntax errors such as missing values, unquoted keys, incorrect delimiters, or unescaped characters.
fix
Ensure each line in your NDJSON file represents a complete and syntactically correct JSON object. When parsing, you can include error handling to skip or log malformed lines:

```python
import ndjson
import json

def parse_ndjson_with_error_handling(filepath):
    valid_records = []
    with open(filepath, 'r', encoding='utf-8') as f:
        for line_num, line in enumerate(f, 1):
            line = line.strip()
            if not line: # Skip empty lines
                continue
            try:
                record = ndjson.loads(line)
                valid_records.append(record)
            except json.JSONDecodeError as e:
                print(f"Error on line {line_num}: {e} - Content: {line[:100]}")
    return valid_records

records = parse_ndjson_with_error_handling('malformed.ndjson')
print(f"Successfully parsed {len(records)} records.")
```
UnicodeEncodeError: 'ascii' codec can't encode characters
Attempting to dump or encode JSON data containing non-ASCII characters without explicitly specifying UTF-8 encoding, often occurring in Python 2 environments or when default encoding is not UTF-8.
fix
Always specify `encoding='utf-8'` when opening files for writing and `ensure_ascii=False` when using `ndjson.dump()` or `ndjson.dumps()` if your data contains non-ASCII characters:

```python
import ndjson

data_with_unicode = [{'name': 'Cáceres', 'city': 'Spain'}, {'name': '京都', 'city': 'Japan'}]

# When dumping to a string
unicode_text = ndjson.dumps(data_with_unicode, ensure_ascii=False)
print(unicode_text)

# When dumping to a file
with open('output_unicode.ndjson', 'w', encoding='utf-8') as f:
    ndjson.dump(data_with_unicode, f, ensure_ascii=False)
```
Upgrade
Version history
0.3.1latest on PyPI · released Feb 25, 2020
Audit
Dependencies

No dependency data recorded yet.

Agent activity
7 hits · last 30 days
node
6
Resources