pyrecord_jar

Pipeline status Ruff License: MIT

A Python module for reading and writing record-jar formatted text files.

What is a “record-jar”?

“Record-jar” is the most well-documented and most-generic name I (astewart) could find for a text file format where data is represented in delimited stanzas of key-value pairs.

The open source book The Art of UNIX Programming by Eric Steven Raymond documents it in the chapter on textual data file formats. It was later written up as an IETF draft, draft-phillips-record-jar-02, which pyrecord_jar’s strict mode follows. Very similar formats are widely used by package managers and by many other Linux tools which produce large volumes of textual data.

Here’s an example of a record-jar file:

Planet: Mercury
Orbital-Radius: 57,910,000 km
Diameter: 4,880 km
Mass: 3.30e23 kg

Planet: Venus
Orbital-Radius: 108,200,000 km
Diameter: 12,103.6 km
Mass: 4.869e24 kg

Planet: Earth
Orbital-Radius: 149,600,000 km
Diameter: 12,756.3 km
Mass: 5.972e24 kg
Moons: Luna

Installing

pyrecord_jar supports Linux and Windows, and every Python version that’s still maintained by the Python core developers (currently 3.11 to 3.15). It has no dependencies outside the standard library, and is fully type-annotated, so type checkers such as mypy check code that uses it.

It isn’t on the Python Package Index yet. Until it is, install it from the GitLab repository:

pip install git+https://gitlab.com/astewart.49c6/pyrecord_jar.git

Python quickstart

The record_jar module works like the standard library’s json module, with load() and loads() to read records, and dump() and dumps() to write them. Each record is a dict of field names to field values.

# Assume the record-jar example above is saved as example.txt.
import record_jar as rj

with open("example.txt", encoding="utf-8") as fp:
    planets = rj.load(fp)

for planet in planets:
    print(planet["Planet"], planet["Diameter"], planet.get("Moons", "-"))

Prints:

Mercury 4,880 km -
Venus 12,103.6 km -
Earth 12,756.3 km Luna

Writing records works the same way:

mars = {"Planet": "Mars", "Moons": "Phobos, Deimos"}
print(rj.dumps([mars]), end="")
Planet: Mars
Moons: Phobos, Deimos

The strict format, encodings and escapes

RecordJarStrictEncoder and RecordJarStrictDecoder implement the stricter format from draft-phillips-record-jar-02, with records separated by %% lines. The strict encoder starts its output with an encoding signature, as the draft recommends:

import record_jar as rj

strict = rj.RecordJarStrictEncoder
records = [{"Planet": "Earth", "Moons": "Luna"}]
print(rj.dumps(records, encoder_class=strict), end="")
%%encoding:UTF-8
Planet : Earth
Moons : Luna
%%

The encoders return text, so save it in the encoding the signature names. To declare another encoding, pass its name as encoding_signature. Characters that encoding can’t represent are written as numeric character references, so the output always fits it:

norway = [{"Language": "Norwegian Bokmål"}]
print(rj.dumps(norway, encoder_class=strict, encoding_signature="US-ASCII"), end="")
%%encoding:US-ASCII
Language : Norwegian Bokmål
%%

Pass ascii_only=True to write pure ASCII whatever the signature says, or encoding_signature=None to leave the signature out. The loose encoder writes no signature unless you ask for one.

When reading, loads() accepts str or bytes. It finds the encoding from a UTF-16 or UTF-32 byte order mark or the encoding signature, and falls back to UTF-8, the default. A signature can only name a character encoding, so one naming a codec such as base64 or unicode_escape raises RecordJarDecoderError. Escapes such as \n and \&, and character references such as å, are turned back into the characters they stand for:

data = b"%%encoding:US-ASCII\nLanguage : Norwegian Bokmål\n%%\n"
print(rj.loads(data, rj.RecordJarStrictDecoder)[0]["Language"])
Norwegian Bokmål

Comments on %% lines are kept with the record that follows them. The strict encoder splits comment lines longer than the draft’s limit of 69 characters, and logs a warning when it does.

Repeated fields

A field name can appear more than once in a record, as Description and Prefix do in the IANA Language Subtag Registry. By default, a repeated field keeps only its last body. repeated_fields="first" keeps only its first body instead. To keep them all, create the decoder with repeated_fields="list", which makes every body a list, in the order the fields appear:

data = b"Type: language\nSubtag: es\nDescription: Spanish\nDescription: Castilian\n%%\n"
print(rj.loads(data, rj.RecordJarStrictDecoder))
print(rj.RecordJarStrictDecoder(repeated_fields="list").decode(data))
[Record({'Type': 'language', 'Subtag': 'es', 'Description': 'Castilian'})]
[Record({'Type': ['language'], 'Subtag': ['es'], 'Description': ['Spanish', 'Castilian']})]

Every body is a list, even for a field that appears once, so code that reads the records doesn’t have to check. The encoders write a list body as one field for each element, so the records write back as they were read.

Command-line quickstart

Installing pyrecord_jar also installs the record_jar command, which converts record-jar files to other formats:

record_jar record_jar json example.txt
[
  {
    "Planet": "Mercury",
    "Orbital-Radius": "57,910,000 km",
    "Diameter": "4,880 km",
    "Mass": "3.30e23 kg"
  },
  ...
]

The input format is record_jar or record_jar_strict, and the output format is one of csv, excel_tab, json, pprint, record_jar or record_jar_strict. So it can also convert between the two record-jar formats:

record_jar record_jar record_jar_strict example.txt
%%encoding:UTF-8
Planet : Mercury
Orbital-Radius : 57,910,000 km
Diameter : 4,880 km
Mass : 3.30e23 kg
%%
...

With no files, it reads from standard input. If the input can’t be read or the output can’t be written, it prints an error and exits with status 1. If the output is piped to a command that stops early, such as head, it exits with status 1 without printing an error. It reads its input as bytes, so it finds the encoding the same way loads() does, and it writes its output in UTF-8. --max-width limits the width of record-jar and pprint output. --repeated-fields first keeps only the first body of a repeated field, and --repeated-fields list keeps every body, and csv and excel_tab output joins them in one cell with --list-separator, "; " by default. In csv and excel_tab output, a cell that a spreadsheet would run as a formula, because it starts with =, +, -, @, a tab or a carriage return, is written with a ' before it; --no-formula-escape writes it as it is. Run record_jar --help for all the options.

Contributing

Bug reports and merge requests are welcome on GitLab. See the contributing guide for how to set up a development environment and submit changes.

Security

To report a security vulnerability, please follow the security policy, not the public issue tracker.

Similar projects

  • Open-RJ is a BSD-licensed C/C++ native library for record-jar parsing. It has cross-language bindings, including to Python 2.2, and it has not been updated for over a decade.

  • record-jar-converter is an Apache-2.0-licensed Java project by Postremus, which converts record-jar files that follow the Phillips draft spec to JSON.

Seriously; are there no others?

License

pyrecord_jar is licensed under the MIT License.

Indices and Tables