Skip to main content

Reading JSON lines (jl) files, recover broken files

Project description

PyPI Version Build Status Code Coverage

This is a tiny library for reading JSON lines (.jl) files, including gzipped and broken files.

JSON lines is a text file format where each line is a single json encoded item.

Why?

Reading a well-formed JSON lines file is a one-liner in Python. But if the file can be broken (this happens when the process writing it is killed), handling all exceptions takes 10x more code, especially when the file is compressed. If file is concatenated from multiple broken archives (some process was writing to the same file multiple times), things get even more complicated.

json-lines handles all this cases for you!

Installation

pip install json-lines

If ujson is installed, it is used to speed up json decoding (which is the main performance bottleneck even for gzipped files).

Usage

In order to read a well-formed json lined file, pass an open file as the first argument to json_lines.reader. The file can be opened in text or binary mode, but if it’s opened in text mode, the encoding must be set correctly:

import json_lines

with open('file.jl', 'rb') as f:
    for item in json_lines.reader(f):
        print(item['x'])

There is also a helper function json_lines.open that recognizes “.gz” and “.gzip” extensions and opens them with gzip:

with json_lines.open('file.jl.gz') as f:
    for item in f:
        print(item['x'])

Handling broken (cut at some point) files is enabled by passing broken=True to json_lines.reader or json_lines.open. They are read while it’s possible to decode the compressed stream and parse json, silently stopping on the first json parse error (only logging a warning). Multiple concatenated broken archives are also supported, the reader will try to skip to the next valid gzip start:

with json_lines.open('file.jl.gz', broken=True) as f:
    for item in f:
        print(item['x'])

License

License is MIT.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

json-lines-0.3.0.tar.gz (4.0 kB view details)

Uploaded Source

File details

Details for the file json-lines-0.3.0.tar.gz.

File metadata

  • Download URL: json-lines-0.3.0.tar.gz
  • Upload date:
  • Size: 4.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for json-lines-0.3.0.tar.gz
Algorithm Hash digest
SHA256 85b4cc8a05dc988673bbd3256c07e0b7add76efbb8b54fd5ade76cc4cacd5bcc
MD5 66ab2fe5733498459a301a2678a0f280
BLAKE2b-256 78e957a97aaf6943dace0c516fe8f46287950176551e1de31db06683dda4cb8f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page