Checking how many agents are working

How this works
Contact
← Blog
A cinematic photograph of a steel filing drawer pulled half open, neat brass tags inside, one tag glowing amber, in teal and steel, the AMARBARO mark and wordmark centred over it.
✎blog post

Reading and writing JSON in Mojo

The short version

mojo-json reads a settings file and writes it back with the same bytes as Python's json.dumps, and parses a 4.6 MB test file about 3.6 times faster.

What this is about

JSON is a way to write data as plain text. It is how many programs store settings and how many web services talk to each other. A JSON file holds named values, lists, numbers, text and true or false.

This article shows how to read a small JSON settings file in Mojo, change one value and write it back. The text we write is exactly the text that Python's json.dumps would write.

Why it matters

A settings file is the first place most programs meet outside data. If your program reads it wrongly, the whole program behaves wrongly. If it writes it differently from other tools, a diff of your file shows many changes when you only changed one value.

Matching Python's output byte for byte means your Mojo program can share files with Python programs without surprises. A script in one language can read what the other wrote, and version control stays quiet when nothing changed.

How to do it, step by step

Say you have a file called settings.json:

{"name": "demo", "volume": 3, "theme": "dark"}

1. Add the library. Use pixi add mojo-json with the steps from the mojo-libs page.

2. Read the file and parse it. Here is the whole program. We ran it on Mojo 1.2.0.

from json import Json, parse


def main() raises:
    var text = open("settings.json", "r").read()
    var doc = parse(text)
    var volume = doc.get("volume").int()
    print(doc.text("theme"), volume)
    doc.set("volume", Json.of(volume + 1))
    var f = open("settings.out.json", "w")
    f.write(doc.dumps(False))
    f.close()
    print(open("settings.out.json", "r").read())

3. See what it did. The program printed dark 3, and then the new file's content:

{"name": "demo", "volume": 4, "theme": "dark"}

4. Compare with Python. Here is the same task in Python:

import json
d = json.load(open("settings.json"))
d["volume"] += 1
print(json.dumps(d))

It prints the same line, byte for byte. Order of the keys is kept, and the spacing is Python's default.

Here is what the key calls mean:

  • parse(text) reads JSON text and gives you a Json value. It stops with an error that names the byte position if the text is not valid.
  • doc.text("theme") takes a text value. doc.get("volume").int() takes a whole number.
  • doc.set("volume", Json.of(4)) sets a value. Json.of makes a value from a number, text or true or false.
  • doc.dumps(False) writes the document in Python's default layout, with a space after each colon and comma. doc.dumps() writes it compact, with no spaces: {"name":"demo","volume":4,"theme":"dark"}.

Why the library is careful

JSON looks easy, but there are many odd cases. The parser follows the strict rules in RFC 8259, the official description of JSON. It passes 95 of 95 files that must be accepted and rejects 188 of 188 that must be rejected, from a public test collection called JSONTestSuite. It does not accept NaN or a trailing comma, because the standard does not allow them. Python's json.loads does accept NaN by default. Our parser rejects it on purpose.

It also keeps the difference between a whole number and a decimal number, as Python does. Whole numbers too large for 64 bits become decimals, rounded the way Python rounds them.

How fast is it

The README measured 20 passes over a 4.6 MB file of 20,000 records, about 500,000 values. Three runs each, on one machine.

parse write (compact) peak memory
Python json 734 to 763 ms 491 to 498 ms 45.4 MB and 54.2 MB
mojo-json 199 to 206 ms 298 to 317 ms 45.3 to 45.7 MB

The memory is mostly the file itself. For a ten-line settings file, none of this matters. For a big log file or a data export, it adds up.

What it does not do

  • No streaming. The whole document is read at once.
  • No object_hook, no big integers, and no NaN or Infinity in parsed input.
  • get and at copy a subtree, and at(i) gets slower for later items. To read single values, use text, opt_f and opt_s.
  • Duplicate keys are kept in order, and get returns the first.
  • Nesting stops with an error at depth 1000.

The library lives in mojo-libs under libs/json, and the older mojo-json repository is read-only.

Common mistakes

Forgetting that the file may be wrong. A person edits a settings file by hand, and people add a comma too many. The parser stops with an error that names the byte position, such as json: <what> at byte N. Catch that error in your program and tell the user where to look.

Calling get in a loop. get copies the part of the document it returns. If you need five values from a nested object, read them with text and the other scalar calls, or keep the nested value in a variable, and do not call get again for each one.

Expecting every number to be a whole number. JSON has one number type, but the library keeps the difference between 3 and 3.0, as Python does. Use int() for whole numbers and the float calls for decimals.

Writing the file in a different layout. dumps() with no argument writes compact text with no spaces. dumps(False) writes Python's default layout. If another tool compares your file byte for byte, pick the layout that tool uses.

Words you may not know

  • JSON: a text format for data, with names, values, lists and numbers.
  • Parse: read text and turn it into data your program can use.
  • Key: the name of a value in a JSON object, such as volume.
  • Byte for byte: exactly the same characters, with no tiny differences.
  • Subtree: one part of a nested document, such as one list inside it.

Try it

  1. Make your own settings.json and run the program above.
  2. Open the mojo-json repository and read its README, then docs/api.md.
  3. Write the same task in Python and run diff on the two output files.
  4. Try an invalid file, such as one with a trailing comma, and read the error.

Comments

No comments yet.

Log in to comment.