Programming Search⌘K

Taskadvanced

Stream-parse a large JSON file

Also called streaming JSON parser, incremental JSON parsing, iterate a JSON array, parse JSON that does not fit in memory, pull-parse JSON.

Read a JSON file that holds one large array, one element at a time, so that the memory used stays the same for a file of any length, and sum one member of each element.

Task

A JSON file can be larger than the memory of the program that reads it. A log export or a database dump is often one large array of objects. The usual call reads the whole file and builds all the values before it returns. For example, Python json.load takes "the JSON document to be deserialized"1 and returns one Python object, so it holds the whole array. A streaming parser reads a small part of the file at a time, and gives each element to the program as soon as the element is complete. The memory then depends on the size of the largest element, not on the size of the file.

Each solution is a function stream_sum(path). The file holds one JSON array of objects. The function returns two numbers: the count of the elements, and the sum of the member amount of all of them.

[{"id": 1, "amount": 10}, {"id": 2, "amount": 25}, {"id": 3, "amount": -5}]

For this file the result is [3, 30]. An empty array gives [0, 0].

The solution holds at most one element and one buffer in memory at a time. It skips all other members, also when they hold nested arrays and objects. It ignores a byte order mark at the start of the file, because RFC 8259 says that parsers "MAY ignore the presence of a byte order mark rather than treating it as an error"2.

The solution reports three errors:

  • invalid-json: the file is not one JSON array. This includes a syntax error in any element, an empty file, NaN, and data after the closing ].
  • bad-record: an element is not an object with a number member amount.
  • not-found: the file does not exist.

A streaming solution finds a syntax error only when it reads the part of the file with the error. It can read many elements before it reports invalid-json. The function returns a result only after the closing ], so a caller never gets the sum of part of the file.

The contract limits the input in two ways. Each amount is an integer, and each partial sum is in the range of a double that holds integers exactly, from -(2^53 - 1) to 2^53 - 1. No object has two members with the same name.

Solutions

The standard libraries of Java, Rust, C, C++ and Bash have no JSON parser. The libraries for these languages also have streaming interfaces. In Java, jackson-core has the incremental (streaming) parser of Jackson, and "All reading is by using JsonParser"3. In Rust, the Serde documentation shows how to process an array "without holding the whole array in memory all at once"4 with a custom visitor. On the command line, jq --stream outputs "arrays of path and leaf values", which "is useful for processing very large inputs"5. The file matrix.yaml records these verdicts.

  • Python. The json module has no streaming parser, but JSONDecoder.raw_decode parses one value from the start of a string and returns the index where the value ends. The documentation says that it "can be used to decode a JSON document from a string that may have extraneous data at the end"1. The solution reads the file in chunks of 65536 characters. It skips the [, then calls raw_decode at the start of each element, and checks for , or ] after it. The text before the current element is dropped when the next chunk is read. The file is opened with the encoding utf-8-sig, which "will skip those three bytes if they appear as the first three bytes in the file"6. The library ijson, "an iterative JSON parser with standard Python iterator interfaces"7, does the same job for any nesting, and ijson.items with the prefix item yields the elements of a top-level array, because "A literal item part is appended when the parser is parsing elements of a JSON array"7.
  • JavaScript and TypeScript (Node.js). JSON.parse takes one string, "The string to parse as JSON"8, so it needs the whole text in memory. The solution reads the file with readSync in chunks of 65536 bytes, and decodes each chunk with a TextDecoder in stream mode. The flag stream is "Set to true if processing the data in chunks"9, so a UTF-8 sequence that is split between two chunks is decoded correctly. A small scanner follows the strings, the escapes and the depth of the brackets, and finds the , or ] at depth 0 that ends each element. JSON.parse then parses the text of that element only, and it throws a SyntaxError if the element is not valid.
  • C#. JsonSerializer.DeserializeAsyncEnumerable can "deserialize root-level JSON arrays in a streaming manner"10. The solution reads each element as a JsonElement from a FileStream, and ToBlockingEnumerable makes the asynchronous sequence a normal one. Another overload has a parameter topLevelValues for a "sequence of top-level JSON values"10, as in JSON Lines.
  • Go. A json.Decoder reads from an io.Reader, so it reads the file in parts. Token returns the [, then Decode reads one element at a time while More "reports whether there is another element in the current array or object being parsed"11. The Go documentation has the same loop in an example that "uses a Decoder to decode a streaming array of JSON objects"11. A last Token must return io.EOF, because "At the end of the input stream, Token returns nil, io.EOF"11. UseNumber keeps each number as its text, and Int64 converts it. Before it makes the decoder, the solution reads the first three bytes with bufio.Reader.Peek and discards a byte order mark.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl. Each case names a file in fixtures/ and gives the count and the sum. The test files build the same texts in temporary files.

  • three-records, one-record and empty-array: the basic shapes. one-record has no line break at the end.
  • pretty, crlf and whitespace: the four white space characters of JSON around the tokens, with LF and CRLF line ends.
  • extra-members: an element with nested arrays, a nested object, true and null. A nested member named amount is not the member of the element.
  • strings-with-brackets: strings that hold ], }, ,, [, {, an escaped quote and an escaped backslash. A scanner that does not follow the strings ends the element too early.
  • non-ascii: names with ü, 😀 and 日本語, which take 2, 4 and 3 bytes in UTF-8.
  • bom: a byte order mark before the [.
  • big-total and negative-total: the sums 9007199254740991 and -9007199254740991, which are 2^53 - 1 and its negative.
  • long-string: a string of 70000 characters, longer than one chunk.
  • many-records: 2500 elements. The digits of one amount are across the offset 65536, so the first chunk ends in the middle of the number.

The cases in cases/errors.jsonl are failures. The toolchain does not load this file yet, so the test files hold these cases by name:

  • invalid-json: a root that is an object, a trailing comma, a missing comma, a file that ends after an element or in an element, data after the array, two arrays, an empty file, an element with no value after a name, and NaN.
  • bad-record: an element that is a number or an array, an object with no amount, and an amount that is a string, null or true.
  • not-found: a path with no file.

Pitfalls

  • A number at the end of a chunk looks complete. When a chunk ends in the middle of a number, the parser sees a shorter number and no error:

This code runs but gives a wrong answer on purpose.

import json

decoder = json.JSONDecoder()
print(decoder.raw_decode('[{"amount": 12', 12))
print(decoder.raw_decode('[{"amount": 123}]', 12))
Output
(12, 14)
(123, 15)

The first call reads 12, but the file holds 123. The Python solution accepts a value only when it ends before the end of the buffer, or when the file has no more data. Otherwise it reads the next chunk and parses the element again. The case many-records tests this.

  • A scanner that does not know strings. A ] in a string is text, not the end of the array:

This code runs but gives a wrong answer on purpose.

text = '[{"note": "a ] b", "amount": 1}]'
end = text.index("]")
print(text[: end + 1])
Output
[{"note": "a ]

The JavaScript scanner keeps one flag that is true in a string and one flag that is true after a backslash, and it counts brackets only outside strings.

  • A UTF-8 character across two chunks. A chunk of bytes can end in the middle of a character. Decode each chunk with a decoder that keeps the incomplete bytes for the next chunk, as TextDecoder does with stream: true9.
  • The sum of part of the file. A streaming parser yields the first elements before it reads the last bytes. If the program acts on each element as it comes, for example it writes rows to a database, a syntax error at the end of the file leaves part of the work done. Collect the results first, or make the work for each element safe to repeat.
  • The memory of one element. A streaming parser holds each element whole. If an element can be very large, the memory is still unbounded. An event parser such as ijson.parse or ijson.basic_parse7, or the tokens of a Jackson JsonParser3, goes down to single values. RFC 8259 also lets a parser "set limits on the size of texts that it accepts"2. Set a limit on the size of an element when the file comes from a source that you do not trust.
  • Large integers in JavaScript. JSON.parse makes each number a double, so an amount above 2^53 - 1 loses digits with no error. The page Read and write JSON shows how the reviver reads the source text of a number.

Code

The build runs the native tests of each language in a pinned toolchain.

stream_sum.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/stream-parse-a-large-json-file/.

import json
from collections.abc import Iterator
from typing import Any, TextIO

CHUNK = 1 << 16  # characters read at a time
SPACE = " \t\n\r"


class BadRecord(Exception):
    """An element of the array is not an object with a number member amount."""


def reject_constant(name: str) -> None:
    # json accepts NaN, Infinity and -Infinity unless this hook refuses them.
    raise ValueError(f"{name} is not a JSON value")


DECODER = json.JSONDecoder(parse_constant=reject_constant)


def elements(f: TextIO) -> Iterator[Any]:
    """Yields the elements of the JSON array in f, one at a time."""
    buf, pos, eof = "", 0, False

    def more() -> bool:
        # Drops the text before pos and reads the next chunk. Returns False at the end of the file.
        nonlocal buf, pos, eof
        chunk = f.read(CHUNK)
        buf, pos, eof = buf[pos:] + chunk, 0, not chunk
        return not eof

    def next_char() -> str:
        # Skips white space and returns the next character, or "" at the end of the file.
        nonlocal pos
        while True:
            while pos < len(buf) and buf[pos] in SPACE:
                pos += 1
            if pos < len(buf) or not more():
                return buf[pos:pos + 1]

    if next_char() != "[":
        raise ValueError("the text does not start with [")
    pos += 1
    if next_char() == "]":
        pos += 1
    else:
        while True:
            next_char()
            while True:
                try:
                    value, end = DECODER.raw_decode(buf, pos)
                    # A number at the end of the buffer can go on in the next chunk.
                    if end < len(buf) or eof:
                        break
                except json.JSONDecodeError:
                    if eof:
                        raise
                more()
            pos = end
            yield value
            c = next_char()
            pos += 1
            if c == "]":
                break
            if c != ",":
                raise ValueError("expected , or ] after an element")
    if next_char() != "":
        raise ValueError("data after the array")


def stream_sum(path: str) -> list[int]:
    """Returns the number of objects in the JSON array in the file, and the sum of their member amount."""
    count = total = 0
    # utf-8-sig drops a byte order mark at the start, which RFC 8259 allows a parser to ignore.
    with open(path, encoding="utf-8-sig") as f:
        for record in elements(f):
            amount = record.get("amount") if isinstance(record, dict) else None
            if not isinstance(amount, int) or isinstance(amount, bool):
                raise BadRecord(f"element {count} has no number member amount")
            count += 1
            total += amount
    return [count, total]
test_stream_sum.py 84 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/stream-parse-a-large-json-file/.

from pathlib import Path

import pytest

from stream_sum import BadRecord, stream_sum


def many_records() -> str:
    # 2500 records. The second space in the first record puts the digits of one amount across the offset 65536, so they come in two chunks.
    records = [f'{{"id": {i},{"  " if i == 0 else " "}"amount": {i * 37 % 1000 - 400}}}' for i in range(2500)]
    return "[" + ",\n".join(records) + "]\n"


CASES = {
    "three-records": ('[{"id": 1, "amount": 10}, {"id": 2, "amount": 25}, {"id": 3, "amount": -5}]\n', [3, 30]),
    "pretty": ('[\n  {\n    "id": 1,\n    "amount": 100\n  },\n  {\n    "id": 2,\n    "amount": 250\n  }\n]\n', [2, 350]),
    "empty-array": ('[]\n', [0, 0]),
    "one-record": ('[{"amount": 7}]', [1, 7]),
    "extra-members": ('[{"id": 1, "tags": ["a", "b"], "meta": {"amount": 999, "x": [1, [2]]}, "amount": 5}, {"amount": 6, "ok": true, "none": null}]\n', [2, 11]),
    "strings-with-brackets": ('[{"note": "a ] b , c } \\" [ {", "amount": 1}, {"note": "\\\\", "amount": 2}, {"note": "]", "amount": 3}]\n', [3, 6]),
    "non-ascii": ('[{"name": "Zürich 😀", "amount": 3}, {"name": "日本語", "amount": 4}]\n', [2, 7]),
    "crlf": ('[\r\n{"amount": 1},\r\n{"amount": 2}\r\n]\r\n', [2, 3]),
    "bom": ('\uFEFF[{"amount": 4}]\n', [1, 4]),
    "big-total": ('[{"amount": 4503599627370496}, {"amount": 4503599627370495}, {"amount": 0}]\n', [3, 9007199254740991]),
    "negative-total": ('[{"amount": -9007199254740991}, {"amount": 0}]\n', [2, -9007199254740991]),
    "whitespace": (' \n\t[ {"amount" : 1} , {"amount":2} ]  \n\n', [2, 3]),
    # A string of 70000 characters is longer than one chunk.
    "long-string": ('[{"note": "' + "x" * 70000 + '", "amount": 8}, {"amount": 9}]\n', [2, 17]),
    "many-records": (many_records(), [2500, 249750]),
}

INVALID = {
    "not-array": '{"amount": 1}\n',
    "trailing-comma": '[{"amount": 1},]\n',
    "missing-comma": '[{"amount": 1} {"amount": 2}]\n',
    "unclosed": '[{"amount": 1},\n',
    "unclosed-element": '[{"amount": 1}, {"amount": 2\n',
    "data-after": '[{"amount": 1}] x\n',
    "two-arrays": '[] []\n',
    "empty-file": '',
    "bad-element": '[{"amount": 1}, {"amount": }]\n',
    "nan": '[{"amount": NaN}]\n',
}

BAD_RECORDS = {
    "not-object": '[1, 2]\n',
    "missing-amount": '[{"amount": 1}, {"id": 2}]\n',
    "string-amount": '[{"amount": "5"}]\n',
    "null-amount": '[{"amount": null}]\n',
    "bool-amount": '[{"amount": true}]\n',
    "nested-array": '[[{"amount": 1}]]\n',
}


def write(tmp_path: Path, text: str) -> str:
    path = tmp_path / "input.json"
    path.write_bytes(text.encode())
    return str(path)


@pytest.mark.parametrize("name", CASES)
def test_cases(tmp_path: Path, name: str) -> None:
    text, want = CASES[name]
    assert stream_sum(write(tmp_path, text)) == want


@pytest.mark.parametrize("name", INVALID)
def test_invalid(tmp_path: Path, name: str) -> None:
    with pytest.raises(ValueError):
        stream_sum(write(tmp_path, INVALID[name]))


@pytest.mark.parametrize("name", BAD_RECORDS)
def test_bad_record(tmp_path: Path, name: str) -> None:
    with pytest.raises(BadRecord):
        stream_sum(write(tmp_path, BAD_RECORDS[name]))


def test_missing(tmp_path: Path) -> None:
    with pytest.raises(FileNotFoundError):
        stream_sum(str(tmp_path / "missing.json"))
StreamSum.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/stream-parse-a-large-json-file/.

using System.Text.Json;
using System.Text.Json.Serialization;

// An element of the array is not an object with a number member amount.
public sealed class BadRecordException(string message) : Exception(message);

public static class StreamSum
{
    // Returns the number of objects in the JSON array in the file, and the sum of their member amount.
    // Throws a JsonException when the file is not a JSON array.
    public static long[] Sum(string path)
    {
        long count = 0, total = 0;
        using FileStream stream = File.OpenRead(path);
        // DeserializeAsyncEnumerable reads a root-level array one element at a time,
        // and holds only a buffer and the current element in memory.
        IAsyncEnumerable<JsonElement> elements = JsonSerializer.DeserializeAsyncEnumerable(stream, StreamJson.Default.JsonElement);
        foreach (JsonElement record in elements.ToBlockingEnumerable())
        {
            if (record.ValueKind != JsonValueKind.Object
                || !record.TryGetProperty("amount", out JsonElement amount)
                || amount.ValueKind != JsonValueKind.Number)
            {
                throw new BadRecordException($"element {count} has no number member amount");
            }
            count++;
            total += amount.GetInt64();
        }
        return [count, total];
    }
}

[JsonSerializable(typeof(JsonElement))]
internal partial class StreamJson : JsonSerializerContext;
StreamSumTests.cs 87 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/stream-parse-a-large-json-file/.

using System.Text;
using System.Text.Json;
using Xunit;

public sealed class StreamSumTests : IDisposable
{
    private readonly string dir = Directory.CreateTempSubdirectory("stream-sum-").FullName;

    public void Dispose() => Directory.Delete(dir, recursive: true);

    private string Write(string text)
    {
        string path = Path.Combine(dir, "input.json");
        File.WriteAllBytes(path, Encoding.UTF8.GetBytes(text));
        return path;
    }

    // 2500 records. The second space in the first record puts the digits of one amount across the offset 65536, so they come in two chunks.
    private static string ManyRecords() =>
        "[" + string.Join(",\n", Enumerable.Range(0, 2500).Select(i => $"{{\"id\": {i},{(i == 0 ? "  " : " ")}\"amount\": {i * 37 % 1000 - 400}}}")) + "]\n";

    public static TheoryData<string, string, long, long> Cases => new()
    {
        { "three-records", "[{\"id\": 1, \"amount\": 10}, {\"id\": 2, \"amount\": 25}, {\"id\": 3, \"amount\": -5}]\n", 3, 30 },
        { "pretty", "[\n  {\n    \"id\": 1,\n    \"amount\": 100\n  },\n  {\n    \"id\": 2,\n    \"amount\": 250\n  }\n]\n", 2, 350 },
        { "empty-array", "[]\n", 0, 0 },
        { "one-record", "[{\"amount\": 7}]", 1, 7 },
        { "extra-members", "[{\"id\": 1, \"tags\": [\"a\", \"b\"], \"meta\": {\"amount\": 999, \"x\": [1, [2]]}, \"amount\": 5}, {\"amount\": 6, \"ok\": true, \"none\": null}]\n", 2, 11 },
        { "strings-with-brackets", "[{\"note\": \"a ] b , c } \\\" [ {\", \"amount\": 1}, {\"note\": \"\\\\\", \"amount\": 2}, {\"note\": \"]\", \"amount\": 3}]\n", 3, 6 },
        { "non-ascii", "[{\"name\": \"Zürich 😀\", \"amount\": 3}, {\"name\": \"日本語\", \"amount\": 4}]\n", 2, 7 },
        { "crlf", "[\r\n{\"amount\": 1},\r\n{\"amount\": 2}\r\n]\r\n", 2, 3 },
        { "bom", "\uFEFF[{\"amount\": 4}]\n", 1, 4 },
        { "big-total", "[{\"amount\": 4503599627370496}, {\"amount\": 4503599627370495}, {\"amount\": 0}]\n", 3, 9007199254740991 },
        { "negative-total", "[{\"amount\": -9007199254740991}, {\"amount\": 0}]\n", 2, -9007199254740991 },
        { "whitespace", " \n\t[ {\"amount\" : 1} , {\"amount\":2} ]  \n\n", 2, 3 },
        // A string of 70000 characters is longer than one chunk.
        { "long-string", "[{\"note\": \"" + new string('x', 70000) + "\", \"amount\": 8}, {\"amount\": 9}]\n", 2, 17 },
        { "many-records", ManyRecords(), 2500, 249750 },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Sums(string name, string text, long count, long total)
    {
        Assert.False(string.IsNullOrEmpty(name));
        Assert.Equal([count, total], StreamSum.Sum(Write(text)));
    }

    [Theory]
    [InlineData("not-array", "{\"amount\": 1}\n")]
    [InlineData("trailing-comma", "[{\"amount\": 1},]\n")]
    [InlineData("missing-comma", "[{\"amount\": 1} {\"amount\": 2}]\n")]
    [InlineData("unclosed", "[{\"amount\": 1},\n")]
    [InlineData("unclosed-element", "[{\"amount\": 1}, {\"amount\": 2\n")]
    [InlineData("data-after", "[{\"amount\": 1}] x\n")]
    [InlineData("two-arrays", "[] []\n")]
    [InlineData("empty-file", "")]
    [InlineData("bad-element", "[{\"amount\": 1}, {\"amount\": }]\n")]
    [InlineData("nan", "[{\"amount\": NaN}]\n")]
    public void Invalid(string name, string text)
    {
        Assert.False(string.IsNullOrEmpty(name));
        string path = Write(text);
        Assert.ThrowsAny<JsonException>(() => StreamSum.Sum(path));
    }

    [Theory]
    [InlineData("not-object", "[1, 2]\n")]
    [InlineData("missing-amount", "[{\"amount\": 1}, {\"id\": 2}]\n")]
    [InlineData("string-amount", "[{\"amount\": \"5\"}]\n")]
    [InlineData("null-amount", "[{\"amount\": null}]\n")]
    [InlineData("bool-amount", "[{\"amount\": true}]\n")]
    [InlineData("nested-array", "[[{\"amount\": 1}]]\n")]
    public void BadRecord(string name, string text)
    {
        Assert.False(string.IsNullOrEmpty(name));
        string path = Write(text);
        Assert.Throws<BadRecordException>(() => StreamSum.Sum(path));
    }

    [Fact]
    public void Missing() =>
        Assert.Throws<FileNotFoundException>(() => StreamSum.Sum(Path.Combine(dir, "missing.json")));
}
streamSum.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/stream-parse-a-large-json-file/.

import { closeSync, openSync, readSync } from "node:fs";

const CHUNK = 1 << 16; // bytes read at a time

// An element of the array is not an object with a number member amount.
export class BadRecordError extends Error {}

// Yields the source text of each element of the JSON array in the file.
// Node.js has no streaming JSON parser, so this scanner finds where each
// element ends, and JSON.parse then checks and parses the element alone.
function* elementTexts(path) {
  const fd = openSync(path, "r");
  try {
    // With stream: true, a UTF-8 sequence split between two chunks is kept for the next call.
    // The decoder also drops a byte order mark at the start.
    const decoder = new TextDecoder("utf-8", { fatal: true });
    const bytes = Buffer.alloc(CHUNK);
    let state = "start"; // start, first (after [), before (after a comma), inside (an element), end
    let text = ""; // the text of the element so far
    let depth = 0;
    let inString = false;
    let escaped = false;
    for (;;) {
      const n = readSync(fd, bytes, 0, CHUNK, null);
      const chunk = decoder.decode(bytes.subarray(0, n), { stream: n > 0 });
      let from = 0; // the start of the current element in chunk
      for (let i = 0; i < chunk.length; i++) {
        const c = chunk[i];
        if (state === "inside") {
          if (inString) {
            if (escaped) escaped = false;
            else if (c === "\\") escaped = true;
            else if (c === '"') inString = false;
            continue;
          }
          if (c === '"') inString = true;
          else if (c === "[" || c === "{") depth++;
          else if (depth > 0 && (c === "]" || c === "}")) depth--;
          else if (depth === 0 && (c === "," || c === "]")) {
            yield text + chunk.slice(from, i);
            text = "";
            state = c === "," ? "before" : "end";
          }
          continue;
        }
        if (c === " " || c === "\t" || c === "\n" || c === "\r") continue;
        if (state === "start" && c === "[") state = "first";
        else if (state === "first" && c === "]") state = "end"; // an empty array
        else if (state === "first" || state === "before") {
          state = "inside";
          from = i;
          i--; // scan this character again as part of the element
        } else throw new SyntaxError(`unexpected ${JSON.stringify(c)} in ${state} state`);
      }
      if (state === "inside") text += chunk.slice(from);
      if (n === 0) break;
    }
    if (state !== "end") throw new SyntaxError("the text is not a complete JSON array");
  } finally {
    closeSync(fd);
  }
}

function isObject(value) {
  return value !== null && typeof value === "object" && !Array.isArray(value);
}

// Returns the number of objects in the JSON array in the file, and the sum of their member amount.
export function streamSum(path) {
  let count = 0;
  let total = 0;
  for (const text of elementTexts(path)) {
    // JSON.parse throws a SyntaxError for an empty or invalid element.
    const record = JSON.parse(text);
    const amount = isObject(record) && Object.hasOwn(record, "amount") ? record.amount : undefined;
    if (typeof amount !== "number") {
      throw new BadRecordError(`element ${count} has no number member amount`);
    }
    count++;
    total += amount;
  }
  return [count, total];
}
streamSum.test.js 87 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/stream-parse-a-large-json-file/.

import assert from "node:assert/strict";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, test } from "node:test";

import { BadRecordError, streamSum } from "./streamSum.js";

// 2500 records. The second space in the first record puts the digits of one amount across the offset 65536, so they come in two chunks.
function manyRecords() {
  const records = Array.from({ length: 2500 }, (_, i) => `{"id": ${i},${i === 0 ? "  " : " "}"amount": ${((i * 37) % 1000) - 400}}`);
  return "[" + records.join(",\n") + "]\n";
}

const CASES = {
  "three-records": ['[{"id": 1, "amount": 10}, {"id": 2, "amount": 25}, {"id": 3, "amount": -5}]\n', [3, 30]],
  "pretty": ['[\n  {\n    "id": 1,\n    "amount": 100\n  },\n  {\n    "id": 2,\n    "amount": 250\n  }\n]\n', [2, 350]],
  "empty-array": ['[]\n', [0, 0]],
  "one-record": ['[{"amount": 7}]', [1, 7]],
  "extra-members": ['[{"id": 1, "tags": ["a", "b"], "meta": {"amount": 999, "x": [1, [2]]}, "amount": 5}, {"amount": 6, "ok": true, "none": null}]\n', [2, 11]],
  "strings-with-brackets": ['[{"note": "a ] b , c } \\" [ {", "amount": 1}, {"note": "\\\\", "amount": 2}, {"note": "]", "amount": 3}]\n', [3, 6]],
  "non-ascii": ['[{"name": "Zürich 😀", "amount": 3}, {"name": "日本語", "amount": 4}]\n', [2, 7]],
  "crlf": ['[\r\n{"amount": 1},\r\n{"amount": 2}\r\n]\r\n', [2, 3]],
  "bom": ['\uFEFF[{"amount": 4}]\n', [1, 4]],
  "big-total": ['[{"amount": 4503599627370496}, {"amount": 4503599627370495}, {"amount": 0}]\n', [3, 9007199254740991]],
  "negative-total": ['[{"amount": -9007199254740991}, {"amount": 0}]\n', [2, -9007199254740991]],
  "whitespace": [' \n\t[ {"amount" : 1} , {"amount":2} ]  \n\n', [2, 3]],
  // A string of 70000 characters is longer than one chunk.
  "long-string": ['[{"note": "' + "x".repeat(70000) + '", "amount": 8}, {"amount": 9}]\n', [2, 17]],
  "many-records": [manyRecords(), [2500, 249750]],
};

const INVALID = {
  "not-array": '{"amount": 1}\n',
  "trailing-comma": '[{"amount": 1},]\n',
  "missing-comma": '[{"amount": 1} {"amount": 2}]\n',
  "unclosed": '[{"amount": 1},\n',
  "unclosed-element": '[{"amount": 1}, {"amount": 2\n',
  "data-after": '[{"amount": 1}] x\n',
  "two-arrays": '[] []\n',
  "empty-file": '',
  "bad-element": '[{"amount": 1}, {"amount": }]\n',
  "nan": '[{"amount": NaN}]\n',
};

const BAD_RECORDS = {
  "not-object": '[1, 2]\n',
  "missing-amount": '[{"amount": 1}, {"id": 2}]\n',
  "string-amount": '[{"amount": "5"}]\n',
  "null-amount": '[{"amount": null}]\n',
  "bool-amount": '[{"amount": true}]\n',
  "nested-array": '[[{"amount": 1}]]\n',
};

const dir = mkdtempSync(join(tmpdir(), "stream-sum-"));
after(() => rmSync(dir, { recursive: true, force: true }));

function write(name, text) {
  const path = join(dir, `${name}.json`);
  writeFileSync(path, text, "utf8");
  return path;
}

for (const [name, [text, want]] of Object.entries(CASES)) {
  test(name, () => {
    assert.deepEqual(streamSum(write(name, text)), want);
  });
}

for (const [name, text] of Object.entries(INVALID)) {
  test(name, () => {
    assert.throws(() => streamSum(write(name, text)), SyntaxError);
  });
}

for (const [name, text] of Object.entries(BAD_RECORDS)) {
  test(name, () => {
    assert.throws(() => streamSum(write(name, text)), BadRecordError);
  });
}

test("missing", () => {
  assert.throws(() => streamSum(join(dir, "missing.json")), { code: "ENOENT" });
});
streamSum.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/stream-parse-a-large-json-file/.

import { closeSync, openSync, readSync } from "node:fs";

const CHUNK = 1 << 16; // bytes read at a time

// An element of the array is not an object with a number member amount.
export class BadRecordError extends Error {}

// Yields the source text of each element of the JSON array in the file.
// Node.js has no streaming JSON parser, so this scanner finds where each
// element ends, and JSON.parse then checks and parses the element alone.
function* elementTexts(path: string): Generator<string> {
  const fd = openSync(path, "r");
  try {
    // With stream: true, a UTF-8 sequence split between two chunks is kept for the next call.
    // The decoder also drops a byte order mark at the start.
    const decoder = new TextDecoder("utf-8", { fatal: true });
    const bytes = Buffer.alloc(CHUNK);
    let state = "start"; // start, first (after [), before (after a comma), inside (an element), end
    let text = ""; // the text of the element so far
    let depth = 0;
    let inString = false;
    let escaped = false;
    for (;;) {
      const n = readSync(fd, bytes, 0, CHUNK, null);
      const chunk = decoder.decode(bytes.subarray(0, n), { stream: n > 0 });
      let from = 0; // the start of the current element in chunk
      for (let i = 0; i < chunk.length; i++) {
        const c = chunk[i];
        if (state === "inside") {
          if (inString) {
            if (escaped) escaped = false;
            else if (c === "\\") escaped = true;
            else if (c === '"') inString = false;
            continue;
          }
          if (c === '"') inString = true;
          else if (c === "[" || c === "{") depth++;
          else if (depth > 0 && (c === "]" || c === "}")) depth--;
          else if (depth === 0 && (c === "," || c === "]")) {
            yield text + chunk.slice(from, i);
            text = "";
            state = c === "," ? "before" : "end";
          }
          continue;
        }
        if (c === " " || c === "\t" || c === "\n" || c === "\r") continue;
        if (state === "start" && c === "[") state = "first";
        else if (state === "first" && c === "]") state = "end"; // an empty array
        else if (state === "first" || state === "before") {
          state = "inside";
          from = i;
          i--; // scan this character again as part of the element
        } else throw new SyntaxError(`unexpected ${JSON.stringify(c)} in ${state} state`);
      }
      if (state === "inside") text += chunk.slice(from);
      if (n === 0) break;
    }
    if (state !== "end") throw new SyntaxError("the text is not a complete JSON array");
  } finally {
    closeSync(fd);
  }
}

function isObject(value: unknown): value is Record<string, unknown> {
  return value !== null && typeof value === "object" && !Array.isArray(value);
}

// Returns the number of objects in the JSON array in the file, and the sum of their member amount.
export function streamSum(path: string): [number, number] {
  let count = 0;
  let total = 0;
  for (const text of elementTexts(path)) {
    // JSON.parse throws a SyntaxError for an empty or invalid element.
    const record: unknown = JSON.parse(text);
    const amount = isObject(record) && Object.hasOwn(record, "amount") ? record.amount : undefined;
    if (typeof amount !== "number") {
      throw new BadRecordError(`element ${count} has no number member amount`);
    }
    count++;
    total += amount;
  }
  return [count, total];
}
streamSum.test.ts 87 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/stream-parse-a-large-json-file/.

import assert from "node:assert/strict";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, test } from "node:test";

import { BadRecordError, streamSum } from "./streamSum.ts";

// 2500 records. The second space in the first record puts the digits of one amount across the offset 65536, so they come in two chunks.
function manyRecords(): string {
  const records = Array.from({ length: 2500 }, (_, i) => `{"id": ${i},${i === 0 ? "  " : " "}"amount": ${((i * 37) % 1000) - 400}}`);
  return "[" + records.join(",\n") + "]\n";
}

const CASES: Record<string, [string, [number, number]]> = {
  "three-records": ['[{"id": 1, "amount": 10}, {"id": 2, "amount": 25}, {"id": 3, "amount": -5}]\n', [3, 30]],
  "pretty": ['[\n  {\n    "id": 1,\n    "amount": 100\n  },\n  {\n    "id": 2,\n    "amount": 250\n  }\n]\n', [2, 350]],
  "empty-array": ['[]\n', [0, 0]],
  "one-record": ['[{"amount": 7}]', [1, 7]],
  "extra-members": ['[{"id": 1, "tags": ["a", "b"], "meta": {"amount": 999, "x": [1, [2]]}, "amount": 5}, {"amount": 6, "ok": true, "none": null}]\n', [2, 11]],
  "strings-with-brackets": ['[{"note": "a ] b , c } \\" [ {", "amount": 1}, {"note": "\\\\", "amount": 2}, {"note": "]", "amount": 3}]\n', [3, 6]],
  "non-ascii": ['[{"name": "Zürich 😀", "amount": 3}, {"name": "日本語", "amount": 4}]\n', [2, 7]],
  "crlf": ['[\r\n{"amount": 1},\r\n{"amount": 2}\r\n]\r\n', [2, 3]],
  "bom": ['\uFEFF[{"amount": 4}]\n', [1, 4]],
  "big-total": ['[{"amount": 4503599627370496}, {"amount": 4503599627370495}, {"amount": 0}]\n', [3, 9007199254740991]],
  "negative-total": ['[{"amount": -9007199254740991}, {"amount": 0}]\n', [2, -9007199254740991]],
  "whitespace": [' \n\t[ {"amount" : 1} , {"amount":2} ]  \n\n', [2, 3]],
  // A string of 70000 characters is longer than one chunk.
  "long-string": ['[{"note": "' + "x".repeat(70000) + '", "amount": 8}, {"amount": 9}]\n', [2, 17]],
  "many-records": [manyRecords(), [2500, 249750]],
};

const INVALID: Record<string, string> = {
  "not-array": '{"amount": 1}\n',
  "trailing-comma": '[{"amount": 1},]\n',
  "missing-comma": '[{"amount": 1} {"amount": 2}]\n',
  "unclosed": '[{"amount": 1},\n',
  "unclosed-element": '[{"amount": 1}, {"amount": 2\n',
  "data-after": '[{"amount": 1}] x\n',
  "two-arrays": '[] []\n',
  "empty-file": '',
  "bad-element": '[{"amount": 1}, {"amount": }]\n',
  "nan": '[{"amount": NaN}]\n',
};

const BAD_RECORDS: Record<string, string> = {
  "not-object": '[1, 2]\n',
  "missing-amount": '[{"amount": 1}, {"id": 2}]\n',
  "string-amount": '[{"amount": "5"}]\n',
  "null-amount": '[{"amount": null}]\n',
  "bool-amount": '[{"amount": true}]\n',
  "nested-array": '[[{"amount": 1}]]\n',
};

const dir = mkdtempSync(join(tmpdir(), "stream-sum-"));
after(() => rmSync(dir, { recursive: true, force: true }));

function write(name: string, text: string): string {
  const path = join(dir, `${name}.json`);
  writeFileSync(path, text, "utf8");
  return path;
}

for (const [name, [text, want]] of Object.entries(CASES)) {
  test(name, () => {
    assert.deepEqual(streamSum(write(name, text)), want);
  });
}

for (const [name, text] of Object.entries(INVALID)) {
  test(name, () => {
    assert.throws(() => streamSum(write(name, text)), SyntaxError);
  });
}

for (const [name, text] of Object.entries(BAD_RECORDS)) {
  test(name, () => {
    assert.throws(() => streamSum(write(name, text)), BadRecordError);
  });
}

test("missing", () => {
  assert.throws(() => streamSum(join(dir, "missing.json")), { code: "ENOENT" });
});
stream_sum.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/stream-parse-a-large-json-file/.

// Package streamsum reads a large JSON array one element at a time.
package streamsum

import (
	"bufio"
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"os"
)

// ErrBadRecord is the error when an element is not an object with a number member amount.
var ErrBadRecord = errors.New("the element has no number member amount")

// StreamSum returns the number of objects in the JSON array in the file, and the sum of their member amount.
func StreamSum(path string) ([2]int64, error) {
	var result [2]int64
	f, err := os.Open(path)
	if err != nil {
		return result, err
	}
	defer f.Close()

	r := bufio.NewReader(f)
	// RFC 8259 allows a parser to ignore a byte order mark. The decoder does not, so skip it here.
	if bom, _ := r.Peek(3); bytes.Equal(bom, []byte("\xef\xbb\xbf")) {
		r.Discard(3)
	}
	dec := json.NewDecoder(r)
	// Keep each number as its text (json.Number), not as a float64.
	dec.UseNumber()

	// Token reads the [ and stops. The decoder then reads one element at a time.
	if tok, err := dec.Token(); err != nil {
		return result, noEOF(err)
	} else if tok != json.Delim('[') {
		return result, fmt.Errorf("the text starts with %v, not [", tok)
	}
	for dec.More() {
		var record any
		if err := dec.Decode(&record); err != nil {
			return result, noEOF(err)
		}
		obj, _ := record.(map[string]any)
		n, ok := obj["amount"].(json.Number)
		if !ok {
			return result, fmt.Errorf("element %d: %w", result[0], ErrBadRecord)
		}
		amount, err := n.Int64()
		if err != nil {
			return result, err
		}
		result[0]++
		result[1] += amount
	}
	if _, err := dec.Token(); err != nil { // the ]
		return result, noEOF(err)
	}
	// Only white space may follow the array.
	if _, err := dec.Token(); err != io.EOF {
		return result, errors.New("data after the JSON array")
	}
	return result, nil
}

// noEOF turns the end of the input into an error that says the text is not complete.
func noEOF(err error) error {
	if err == io.EOF {
		return io.ErrUnexpectedEOF
	}
	return err
}
stream_sum_test.go 105 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/stream-parse-a-large-json-file/.

package streamsum

import (
	"errors"
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func write(t *testing.T, data string) string {
	t.Helper()
	path := filepath.Join(t.TempDir(), "input.json")
	if err := os.WriteFile(path, []byte(data), 0o644); err != nil {
		t.Fatal(err)
	}
	return path
}

// 2500 records. The second space in the first record puts the digits of one amount across the offset 65536, so they come in two chunks.
func manyRecords() string {
	records := make([]string, 2500)
	for i := range records {
		space := " "
		if i == 0 {
			space = "  "
		}
		records[i] = fmt.Sprintf(`{"id": %d,%s"amount": %d}`, i, space, i*37%1000-400)
	}
	return "[" + strings.Join(records, ",\n") + "]\n"
}

func TestCases(t *testing.T) {
	cases := []struct {
		name, data string
		want       [2]int64
	}{
		{"three-records", `[{"id": 1, "amount": 10}, {"id": 2, "amount": 25}, {"id": 3, "amount": -5}]` + "\n", [2]int64{3, 30}},
		{"pretty", "[\n  {\n    \"id\": 1,\n    \"amount\": 100\n  },\n  {\n    \"id\": 2,\n    \"amount\": 250\n  }\n]\n", [2]int64{2, 350}},
		{"empty-array", `[]` + "\n", [2]int64{0, 0}},
		{"one-record", `[{"amount": 7}]`, [2]int64{1, 7}},
		{"extra-members", `[{"id": 1, "tags": ["a", "b"], "meta": {"amount": 999, "x": [1, [2]]}, "amount": 5}, {"amount": 6, "ok": true, "none": null}]` + "\n", [2]int64{2, 11}},
		{"strings-with-brackets", `[{"note": "a ] b , c } \" [ {", "amount": 1}, {"note": "\\", "amount": 2}, {"note": "]", "amount": 3}]` + "\n", [2]int64{3, 6}},
		{"non-ascii", `[{"name": "Zürich 😀", "amount": 3}, {"name": "日本語", "amount": 4}]` + "\n", [2]int64{2, 7}},
		{"crlf", "[\r\n{\"amount\": 1},\r\n{\"amount\": 2}\r\n]\r\n", [2]int64{2, 3}},
		{"bom", "\uFEFF[{\"amount\": 4}]\n", [2]int64{1, 4}},
		{"big-total", `[{"amount": 4503599627370496}, {"amount": 4503599627370495}, {"amount": 0}]` + "\n", [2]int64{3, 9007199254740991}},
		{"negative-total", `[{"amount": -9007199254740991}, {"amount": 0}]` + "\n", [2]int64{2, -9007199254740991}},
		{"whitespace", " \n\t[ {\"amount\" : 1} , {\"amount\":2} ]  \n\n", [2]int64{2, 3}},
		// A string of 70000 characters is longer than one chunk.
		{"long-string", `[{"note": "` + strings.Repeat("x", 70000) + `", "amount": 8}, {"amount": 9}]` + "\n", [2]int64{2, 17}},
		{"many-records", manyRecords(), [2]int64{2500, 249750}},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			got, err := StreamSum(write(t, c.data))
			if err != nil || got != c.want {
				t.Errorf("StreamSum = %v, %v; want %v, nil", got, err, c.want)
			}
		})
	}
}

func TestInvalid(t *testing.T) {
	cases := []struct {
		name, data string
		badRecord  bool
	}{
		{"not-array", `{"amount": 1}` + "\n", false},
		{"trailing-comma", `[{"amount": 1},]` + "\n", false},
		{"missing-comma", `[{"amount": 1} {"amount": 2}]` + "\n", false},
		{"unclosed", `[{"amount": 1},` + "\n", false},
		{"unclosed-element", `[{"amount": 1}, {"amount": 2` + "\n", false},
		{"data-after", `[{"amount": 1}] x` + "\n", false},
		{"two-arrays", `[] []` + "\n", false},
		{"empty-file", "", false},
		{"bad-element", `[{"amount": 1}, {"amount": }]` + "\n", false},
		{"nan", `[{"amount": NaN}]` + "\n", false},
		{"not-object", `[1, 2]` + "\n", true},
		{"missing-amount", `[{"amount": 1}, {"id": 2}]` + "\n", true},
		{"string-amount", `[{"amount": "5"}]` + "\n", true},
		{"null-amount", `[{"amount": null}]` + "\n", true},
		{"bool-amount", `[{"amount": true}]` + "\n", true},
		{"nested-array", `[[{"amount": 1}]]` + "\n", true},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			_, err := StreamSum(write(t, c.data))
			if err == nil || errors.Is(err, ErrBadRecord) != c.badRecord {
				t.Errorf("err = %v, want an error with ErrBadRecord %v", err, c.badRecord)
			}
		})
	}
}

func TestMissing(t *testing.T) {
	if _, err := StreamSum(filepath.Join(t.TempDir(), "missing.json")); !errors.Is(err, fs.ErrNotExist) {
		t.Errorf("err = %v, want fs.ErrNotExist", err)
	}
}

References

  1. The Python Standard Library, json, Python 3.14, json.load; JSONDecoder.raw_decode; parse_constant
  2. T. Bray (Ed.), RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format, December 2017, 2 JSON Grammar; 8.1 Character Encoding; 9 Parsers
  3. jackson-core, the core of the Jackson JSON processor, README, Overview; Usage, general
  4. Serde documentation, Array of values without buffering
  5. jq manual, Invoking jq, --stream
  6. The Python Standard Library, codecs, Python 3.14, Encodings and Unicode, utf-8-sig
  7. ijson, an iterative JSON parser for Python, README, Usage (items, kvitems, parse, basic_parse); Backends
  8. MDN Web Docs, JSON.parse(), Parameters, text
  9. MDN Web Docs, TextDecoder.decode(), Parameters, options.stream; Exceptions
  10. .NET API reference, JsonSerializer.DeserializeAsyncEnumerable, Overloads; the parameter topLevelValues
  11. Go standard library, package encoding/json, func NewDecoder; Decoder.Decode, Example (Stream); Decoder.More; Decoder.Token; Decoder.UseNumber

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source