Programming Search⌘K

Taskcore

Read and write JSON

Also called parse JSON, serialize JSON, encode and decode JSON, get a value from JSON, write canonical JSON.

Parse a JSON text with the standard library, follow a path of names and indexes to one value, and write that value back as canonical JSON with no loss of integer digits.

Task

Parse a JSON text, get one value from it, and write that value back as JSON text. Two texts with the same data give the same output.

Each solution is a function json_get(text, path). The path is a list of steps from the root. In an object, a step is the name of a member. In an array, a step is a decimal index with no sign and no leading zero, as in a JSON Pointer (RFC 6901, section 4). An empty path selects the root.

The canonical output follows four rules:

  • There is no white space outside strings.
  • The members of each object are sorted by name in code point order.
  • Each integer has all its digits, and -0 becomes 0.
  • A string escapes " and \. The control characters below U+0020 become \b, \t, \n, \f, \r or \u00 and two lowercase hexadecimal digits. Every other character is written as itself in UTF-8.

They are close to the JSON Canonicalization Scheme of RFC 8785, with two differences. RFC 8785 sorts names by UTF-16 code units, and it writes each number as an IEEE 754 double. This task keeps integers exact.

The solution reports two errors. invalid-json means the text is not a JSON text as RFC 8259 defines it. not-found means the path names no value.

The contract limits the input in three ways. Each number is an integer, because the libraries write fractions and exponents in different forms. No string holds an unpaired surrogate, because RFC 8259 (section 8.2) says that the behaviour of a parser is then unpredictable. No string holds U+2028 or U+2029, because the Go encoder always escapes them (see the pitfalls).

Solutions

The standard libraries of Java, Rust, C, C++ and Bash have no JSON parser, so this page has no solution in those languages. The usual choices are Jackson or Gson for Java, serde_json for Rust, cJSON or Jansson for C, nlohmann/json for C++, and jq for Bash. The file matrix.yaml records these verdicts.

  • Python. json.loads parses the text, and each JSON integer becomes an int with all its digits. json.loads accepts NaN, Infinity and -Infinity by default. The parse_constant hook gets these names, so the solution raises a ValueError there. json.dumps with ensure_ascii=False, separators=(",", ":") and sort_keys=True writes the canonical form. Python sorts strings by code point. An invalid text raises json.JSONDecodeError, a subclass of ValueError. A missing value raises KeyError.
  • JavaScript and TypeScript (Node.js). JSON.parse makes each number a double. The reviver gets a third argument, context, with the source text of each number in context.source. The solution makes a BigInt from that text. JSON.stringify throws a TypeError on a BigInt, so a short function writes the arrays and objects. It still calls JSON.stringify for each string. It sorts the names with Buffer.compare on their UTF-8 bytes, because UTF-8 byte order is code point order. An invalid text throws a SyntaxError, and a missing value throws a RangeError. The TypeScript file adds types only.
  • C#. JsonDocument.Parse keeps each number as its source text, so GetRawText gives all the digits. With the default options, it rejects comments and trailing commas, and it throws a JsonException. The encoders of System.Text.Json escape non-ASCII characters, so the solution writes the output with a StringBuilder and escapes each string itself. It sorts the names by their UTF-8 bytes. A missing value throws KeyNotFoundException.
  • Go. json.NewDecoder with UseNumber keeps each number as a json.Number, which is its source text. Decode reads one value and stops, so the solution then calls Token and requires io.EOF. An Encoder with SetEscapeHTML(false) writes the value. The encoder sorts the keys of a map by their bytes. A small function changes -0 to 0. An invalid text gives a *json.SyntaxError or io.ErrUnexpectedEOF, and a missing value gives ErrNotFound.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl. Each case gives the text, the path, and the canonical output.

  • big-int, beyond-int64 and int64-bounds: 9007199254740993 is 2^53 + 1, the first integer that a double cannot hold. 18446744073709551617 is above the range of a 64-bit integer. All the digits stay.
  • negative-zero: [-0, 0] gives [0,0].
  • duplicate-name and duplicate-name-whole: {"a": 1, "a": 2}. RFC 8259 says that names SHOULD be unique, and that many parsers report only the last pair. Here the last member wins.
  • key-order-ascii: the names "10" and "9" sort as strings, so "10" comes first. A JavaScript object puts integer-like names first in numeric order, so Object.keys gives "9" first.
  • key-order-astral: "fi" (U+FB01) sorts before "😀" (U+1F600) in code point order. In UTF-16 order the emoji comes first, because its first code unit is 0xD83D.
  • non-ascii and escaped-non-ascii: "é😀" in the input gives "é😀" in the output.
  • escapes and control-chars: \/ becomes /, U+001F becomes \u001f, and U+007F stays as itself, because RFC 8259 requires escapes only below U+0020.
  • html-chars: <, >, & and ' stay as they are.
  • empty-containers, scalar-root and string-root: {}, [], "" and a root that is not an array or object. RFC 8259 allows any value at the root.
  • whitespace and whitespace-inside: the four white space characters around the tokens.
  • null-member and false-member: a member with the value null or false is found. A test for truth would miss it.
  • proto-name and proto-path: the names __proto__ and constructor are normal names. JSON.parse makes them own properties of the object.
  • array-index-10, numeric-name and deep-path: the index 10, an object member named "0", and a path of six steps.

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 trailing comma, single quotes, a name with no quotes, NaN, Infinity, -Infinity, 01, +1, 0x10, an empty text, data after the value, a comment, a raw tab in a string, \x41, and a text with no end. RFC 8259 allows none of these.
  • byte-order-mark: RFC 8259 (section 8.1) says that a parser MAY ignore a byte order mark. All four libraries reject it in a string, so the contract makes it an error.
  • not-found: a missing name, the inherited name toString, the name length on an array, the indexes 2, 01, -1, +1 and ١ (ARABIC-INDIC DIGIT ONE) on an array of two, and a step into a number or into null.

The contract also limits the size of the input. The Python int conversion refuses more than 4300 digits by default, and json.loads uses it. JsonDocument refuses more than 64 levels of nesting by default.

Pitfalls

  • A JavaScript number loses digits. JSON.parse makes each number a double, and the last digit changes with no error. The reviver can read the source text:

This code runs but gives a wrong answer on purpose.

const text = '{"id": 9007199254740993}';
console.log(JSON.parse(text).id);
const exact = JSON.parse(text, (key, value, context) =>
  typeof value === "number" ? BigInt(context.source) : value,
);
console.log(exact.id);
try {
  JSON.stringify(exact);
} catch (e) {
  console.log(e.name);
}
Output
9007199254740992
9007199254740993n
TypeError
  • An inherited property looks like a member. In JavaScript, value[name] also finds the properties of Object.prototype. Use Object.hasOwn:
const value = JSON.parse('{"a": 1}');
console.log(typeof value["toString"], Object.hasOwn(value, "toString"));
Output
function false
  • Python reads and writes NaN. json.loads accepts NaN and Infinity, and json.dumps writes them. Both are invalid JSON:

This code runs but gives a wrong answer on purpose.

import json

print(json.loads("[NaN, Infinity]"))
print(json.dumps(float("nan")))
try:
    json.dumps(float("nan"), allow_nan=False)
except ValueError as e:
    print("ValueError:", e)
Output
[nan, inf]
NaN
ValueError: Out of range float values are not JSON compliant: nan

Give allow_nan=False to json.dumps, and a parse_constant that raises an error to json.loads.

  • A repeated name is silently dropped. Each solution keeps the last member. If two parts of a system read the same object, and one keeps the first member, they see different data. Reject repeated names when the text comes from a source that you do not trust. In Python, object_pairs_hook gets all the pairs:
import json


def unique(pairs):
    names = [name for name, _ in pairs]
    if len(names) != len(set(names)):
        raise ValueError(f"repeated name in {names}")
    return dict(pairs)


print(json.loads('{"role": "user", "role": "admin"}'))
try:
    json.loads('{"role": "user", "role": "admin"}', object_pairs_hook=unique)
except ValueError as e:
    print("ValueError:", e)
Output
{'role': 'admin'}
ValueError: repeated name in ['role', 'role']

In C#, JsonDocument keeps both members by default. The option AllowDuplicateProperties = false makes JsonDocument.Parse throw a JsonException:

using System.Text.Json;

string text = """{"role": "user", "role": "admin"}""";
using (JsonDocument document = JsonDocument.Parse(text))
{
    Console.WriteLine(document.RootElement.EnumerateObject().Count());
}
try
{
    JsonDocument.Parse(text, new JsonDocumentOptions { AllowDuplicateProperties = false });
}
catch (JsonException e)
{
    Console.WriteLine(e.Message);
}
Output
2
Duplicate property 'role' encountered during deserialization.
  • The Go decoder ignores data after the value. Decoder.Decode reads one value and stops. It also makes a number a float64 unless UseNumber is called:

This code runs but gives a wrong answer on purpose.

package main

import (
	"encoding/json"
	"fmt"
	"strings"
)

func main() {
	dec := json.NewDecoder(strings.NewReader("[9007199254740993] x"))
	var value any
	err := dec.Decode(&value)
	fmt.Println(value, err)
	_, err = dec.Token()
	fmt.Println(err)
}
Output
[9.007199254740992e+15] <nil>
invalid character 'x' looking for beginning of value

json.Unmarshal rejects data after the value, but it has no UseNumber.

  • Go escapes HTML characters. json.Marshal writes <, > and & as escapes. An Encoder with SetEscapeHTML(false) writes them as they are, but it still escapes U+2028 and U+2029:
package main

import (
	"encoding/json"
	"fmt"
	"os"
)

func main() {
	s := "<b>&\u2028"
	out, _ := json.Marshal(s)
	fmt.Println(string(out))
	enc := json.NewEncoder(os.Stdout)
	enc.SetEscapeHTML(false)
	enc.Encode(s)
}
Output
"\u003cb\u003e\u0026\u2028"
"<b>&\u2028"
  • C# escapes all non-ASCII characters by default. The default encoder of System.Text.Json escapes non-ASCII characters and HTML characters. JavaScriptEncoder.UnsafeRelaxedJsonEscaping keeps <, & and é, but it still escapes the emoji:

This code runs but gives a wrong answer on purpose.

using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;

string s = "é<&>😀";
foreach (JavaScriptEncoder? encoder in new[] { null, JavaScriptEncoder.UnsafeRelaxedJsonEscaping })
{
    using var stream = new MemoryStream();
    using (var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Encoder = encoder }))
    {
        writer.WriteStringValue(s);
    }
    Console.WriteLine(Encoding.UTF8.GetString(stream.ToArray()));
}
Output
"\u00E9\u003C\u0026\u003E\uD83D\uDE00"
"é<&>\uD83D\uDE00"

The output is valid JSON in both cases. It is not the canonical form, so the C# solution escapes the strings itself.

Code

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

json_get.pyI0tests passRawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-and-write-json/.

import json
import re

# An array index: ASCII digits, no sign, no leading zero.
INDEX = re.compile(r"0|[1-9][0-9]*")


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


def json_get(text: str, path: list[str]) -> str:
    """Returns the value at path in the JSON text, as canonical JSON."""
    value = json.loads(text, parse_constant=reject_constant)
    for step in path:
        if isinstance(value, dict) and step in value:
            value = value[step]
        elif isinstance(value, list) and INDEX.fullmatch(step) and int(step) < len(value):
            value = value[int(step)]
        else:
            raise KeyError(step)
    return json.dumps(
        value,
        ensure_ascii=False,
        allow_nan=False,
        separators=(",", ":"),
        sort_keys=True,
    )
test_json_get.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-and-write-json/.

import json

import pytest

from json_get import json_get

# name: (text, path, the canonical JSON of the value at path)
CASES = {
    "member": ('{"name": "Ada", "born": 1815}', ["name"], '"Ada"'),
    "whole-document": ('{"b": [1, 2], "a": true}', [], '{"a":true,"b":[1,2]}'),
    "nested-path": ('{"user": {"tags": ["x", "y"]}}', ["user", "tags", "1"], '"y"'),
    "big-int": ('{"id": 9007199254740993}', ["id"], "9007199254740993"),
    "beyond-int64": (
        "[18446744073709551617, -18446744073709551617]",
        [],
        "[18446744073709551617,-18446744073709551617]",
    ),
    "int64-bounds": ("[-9223372036854775808, 9223372036854775807]", [], "[-9223372036854775808,9223372036854775807]"),
    "negative-zero": ("[-0, 0]", [], "[0,0]"),
    "duplicate-name": ('{"a": 1, "a": 2}', ["a"], "2"),
    "duplicate-name-whole": ('{"a": 1, "b": 0, "a": {"c": 3}}', [], '{"a":{"c":3},"b":0}'),
    "array-index-10": ('[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "ten"]', ["10"], '"ten"'),
    "numeric-name": ('{"0": "zero", "1": "one"}', ["0"], '"zero"'),
    "key-order-ascii": ('{"b": 1, "a": 2, "B": 3, "10": 4, "9": 5}', [], '{"10":4,"9":5,"B":3,"a":2,"b":1}'),
    "key-order-prefix": ('{"ab": 1, "a": 2, "": 3}', [], '{"":3,"a":2,"ab":1}'),
    "key-order-astral": ('{"😀": 1, "fi": 2, "é": 3}', [], '{"é":3,"fi":2,"😀":1}'),
    "non-ascii": ('["Zürich", "日本語", "😀"]', [], '["Zürich","日本語","😀"]'),
    "escaped-non-ascii": ('["\\u00e9\\ud83d\\ude00"]', ["0"], '"é😀"'),
    "escapes": ('["q\\" b\\\\ s\\/ t\\t n\\n r\\r"]', [], '["q\\" b\\\\ s/ t\\t n\\n r\\r"]'),
    "control-chars": ('["\\u0000\\u001f\\b\\f\\u007f"]', [], '["\\u0000\\u001f\\b\\f\x7f"]'),
    "html-chars": ('{"html": "<a href=\'x\'>&amp;</a>"}', ["html"], "\"<a href='x'>&amp;</a>\""),
    "empty-containers": ('{"a": {}, "b": [], "c": ""}', [], '{"a":{},"b":[],"c":""}'),
    "scalar-root": ("42", [], "42"),
    "string-root": ('"text"', [], '"text"'),
    "whitespace": (" \n\ttrue\r\n ", [], "true"),
    "whitespace-inside": ('\n{ "a" :\t[ 1 , 2 ] }\r\n', [], '{"a":[1,2]}'),
    "deep-path": ('{"a": [{"b": [[1, {"c": "deep"}]]}]}', ["a", "0", "b", "0", "1", "c"], '"deep"'),
    "null-member": ('{"a": null}', ["a"], "null"),
    "false-member": ('{"a": false, "b": 0}', ["a"], "false"),
    "proto-name": ('{"__proto__": {"x": 1}, "constructor": 2}', [], '{"__proto__":{"x":1},"constructor":2}'),
    "proto-path": ('{"__proto__": {"x": 1}}', ["__proto__", "x"], "1"),
}

# name: (text, path); the text is not JSON
INVALID = {
    "trailing-comma-array": ("[1, 2,]", []),
    "trailing-comma-object": ('{"a": 1,}', []),
    "single-quotes": ("{'a': 1}", []),
    "unquoted-name": ("{a: 1}", []),
    "nan": ("[NaN]", []),
    "infinity": ("[Infinity]", []),
    "negative-infinity": ("-Infinity", []),
    "leading-zero": ("[01]", []),
    "plus-sign": ("+1", []),
    "hex-number": ("0x10", []),
    "empty-text": ("", []),
    "whitespace-only": (" \n", []),
    "trailing-data": ("[1] x", []),
    "two-values": ("1 2", []),
    "comment": ('{"a": 1} // note', []),
    "byte-order-mark": ('\ufeff{"a": 1}', []),
    "raw-control-char": ('["a\tb"]', []),
    "bad-escape": ('["\\x41"]', []),
    "unclosed": ("[1, 2", []),
}

# name: (text, path); the path names no value
NOT_FOUND = {
    "missing-name": ('{"a": 1}', ["b"]),
    "inherited-name": ('{"a": 1}', ["toString"]),
    "array-length": ("[1, 2]", ["length"]),
    "index-out-of-range": ("[1, 2]", ["2"]),
    "index-leading-zero": ("[1, 2]", ["01"]),
    "index-negative": ("[1, 2]", ["-1"]),
    "index-plus": ("[1, 2]", ["+1"]),
    "index-non-ascii-digit": ("[1, 2]", ["١"]),
    "through-scalar": ('{"a": 1}', ["a", "b"]),
    "through-null": ('{"a": null}', ["a", "b"]),
}


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


@pytest.mark.parametrize("name", INVALID)
def test_invalid_json(name: str) -> None:
    text, path = INVALID[name]
    with pytest.raises(ValueError):
        json_get(text, path)


@pytest.mark.parametrize("name", NOT_FOUND)
def test_not_found(name: str) -> None:
    text, path = NOT_FOUND[name]
    with pytest.raises(KeyError):
        json_get(text, path)


def test_decode_error_type() -> None:
    # JSONDecodeError is a subclass of ValueError. It gives the position of the error: here the comma.
    with pytest.raises(json.JSONDecodeError) as info:
        json_get("[1, 2,]", [])
    assert (info.value.lineno, info.value.colno) == (1, 6)
JsonGet.csI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-json/.

using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;

public static partial class CanonicalJson
{
    // An array index: ASCII digits, no sign, no leading zero.
    [GeneratedRegex("^(?:0|[1-9][0-9]*)$")]
    private static partial Regex Index();

    // Returns the value at path in the JSON text, as canonical JSON.
    // Throws a JsonException when the text is not JSON, and a
    // KeyNotFoundException when the path names no value.
    public static string JsonGet(string text, IReadOnlyList<string> path)
    {
        // JsonDocument keeps each number as its text, so no digit is lost.
        using JsonDocument document = JsonDocument.Parse(text);
        JsonElement value = document.RootElement;
        foreach (string step in path)
        {
            value = Step(value, step) ?? throw new KeyNotFoundException($"no value at \"{step}\"");
        }
        var output = new StringBuilder();
        Write(value, output);
        return output.ToString();
    }

    private static JsonElement? Step(JsonElement value, string step)
    {
        if (value.ValueKind == JsonValueKind.Object)
        {
            // JsonDocument keeps every member of a repeated name. The last one wins.
            JsonElement? found = null;
            foreach (JsonProperty member in value.EnumerateObject())
            {
                if (member.Name == step)
                {
                    found = member.Value;
                }
            }
            return found;
        }
        if (value.ValueKind == JsonValueKind.Array && Index().IsMatch(step)
            && int.TryParse(step, NumberStyles.None, CultureInfo.InvariantCulture, out int i)
            && i < value.GetArrayLength())
        {
            return value[i];
        }
        return null;
    }

    // UTF-8 byte order is code point order. string.CompareOrdinal uses UTF-16 code units.
    private static int ByCodePoint(string a, string b) =>
        Encoding.UTF8.GetBytes(a).AsSpan().SequenceCompareTo(Encoding.UTF8.GetBytes(b));

    // Writes the value as canonical JSON. The encoders of System.Text.Json
    // escape non-ASCII characters, so this writer escapes the strings itself.
    private static void Write(JsonElement value, StringBuilder output)
    {
        switch (value.ValueKind)
        {
            case JsonValueKind.Object:
                var members = new Dictionary<string, JsonElement>();
                foreach (JsonProperty member in value.EnumerateObject())
                {
                    members[member.Name] = member.Value;
                }
                var names = members.Keys.ToList();
                names.Sort(ByCodePoint);
                output.Append('{');
                for (int i = 0; i < names.Count; i++)
                {
                    if (i > 0)
                    {
                        output.Append(',');
                    }
                    WriteString(names[i], output);
                    output.Append(':');
                    Write(members[names[i]], output);
                }
                output.Append('}');
                break;
            case JsonValueKind.Array:
                output.Append('[');
                int n = 0;
                foreach (JsonElement element in value.EnumerateArray())
                {
                    if (n++ > 0)
                    {
                        output.Append(',');
                    }
                    Write(element, output);
                }
                output.Append(']');
                break;
            case JsonValueKind.String:
                WriteString(value.GetString()!, output);
                break;
            case JsonValueKind.Number:
                string number = value.GetRawText();
                output.Append(number == "-0" ? "0" : number);
                break;
            default:
                output.Append(value.GetRawText()); // true, false or null
                break;
        }
    }

    private static void WriteString(string s, StringBuilder output)
    {
        output.Append('"');
        foreach (char c in s)
        {
            switch (c)
            {
                case '"': output.Append("\\\""); break;
                case '\\': output.Append("\\\\"); break;
                case '\b': output.Append("\\b"); break;
                case '\f': output.Append("\\f"); break;
                case '\n': output.Append("\\n"); break;
                case '\r': output.Append("\\r"); break;
                case '\t': output.Append("\\t"); break;
                case < ' ': output.Append($"\\u{(int)c:x4}"); break;
                default: output.Append(c); break;
            }
        }
        output.Append('"');
    }
}
JsonGetTests.cs 104 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-json/.

using System.Text.Json;
using Xunit;

public sealed class JsonGetTests
{
    // case, text, path, the canonical JSON of the value at path
    public static TheoryData<string, string, string[], string> Cases => new()
    {
        { "member", "{\"name\": \"Ada\", \"born\": 1815}", ["name"], "\"Ada\"" },
        { "whole-document", "{\"b\": [1, 2], \"a\": true}", [], "{\"a\":true,\"b\":[1,2]}" },
        { "nested-path", "{\"user\": {\"tags\": [\"x\", \"y\"]}}", ["user", "tags", "1"], "\"y\"" },
        { "big-int", "{\"id\": 9007199254740993}", ["id"], "9007199254740993" },
        { "beyond-int64", "[18446744073709551617, -18446744073709551617]", [], "[18446744073709551617,-18446744073709551617]" },
        { "int64-bounds", "[-9223372036854775808, 9223372036854775807]", [], "[-9223372036854775808,9223372036854775807]" },
        { "negative-zero", "[-0, 0]", [], "[0,0]" },
        { "duplicate-name", "{\"a\": 1, \"a\": 2}", ["a"], "2" },
        { "duplicate-name-whole", "{\"a\": 1, \"b\": 0, \"a\": {\"c\": 3}}", [], "{\"a\":{\"c\":3},\"b\":0}" },
        { "array-index-10", "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, \"ten\"]", ["10"], "\"ten\"" },
        { "numeric-name", "{\"0\": \"zero\", \"1\": \"one\"}", ["0"], "\"zero\"" },
        { "key-order-ascii", "{\"b\": 1, \"a\": 2, \"B\": 3, \"10\": 4, \"9\": 5}", [], "{\"10\":4,\"9\":5,\"B\":3,\"a\":2,\"b\":1}" },
        { "key-order-prefix", "{\"ab\": 1, \"a\": 2, \"\": 3}", [], "{\"\":3,\"a\":2,\"ab\":1}" },
        { "key-order-astral", "{\"😀\": 1, \"fi\": 2, \"é\": 3}", [], "{\"é\":3,\"fi\":2,\"😀\":1}" },
        { "non-ascii", "[\"Zürich\", \"日本語\", \"😀\"]", [], "[\"Zürich\",\"日本語\",\"😀\"]" },
        { "escaped-non-ascii", "[\"\\u00e9\\ud83d\\ude00\"]", ["0"], "\"é😀\"" },
        { "escapes", "[\"q\\\" b\\\\ s\\/ t\\t n\\n r\\r\"]", [], "[\"q\\\" b\\\\ s/ t\\t n\\n r\\r\"]" },
        { "control-chars", "[\"\\u0000\\u001f\\b\\f\\u007f\"]", [], "[\"\\u0000\\u001f\\b\\f\u007f\"]" },
        { "html-chars", "{\"html\": \"<a href='x'>&amp;</a>\"}", ["html"], "\"<a href='x'>&amp;</a>\"" },
        { "empty-containers", "{\"a\": {}, \"b\": [], \"c\": \"\"}", [], "{\"a\":{},\"b\":[],\"c\":\"\"}" },
        { "scalar-root", "42", [], "42" },
        { "string-root", "\"text\"", [], "\"text\"" },
        { "whitespace", " \n\ttrue\r\n ", [], "true" },
        { "whitespace-inside", "\n{ \"a\" :\t[ 1 , 2 ] }\r\n", [], "{\"a\":[1,2]}" },
        { "deep-path", "{\"a\": [{\"b\": [[1, {\"c\": \"deep\"}]]}]}", ["a", "0", "b", "0", "1", "c"], "\"deep\"" },
        { "null-member", "{\"a\": null}", ["a"], "null" },
        { "false-member", "{\"a\": false, \"b\": 0}", ["a"], "false" },
        { "proto-name", "{\"__proto__\": {\"x\": 1}, \"constructor\": 2}", [], "{\"__proto__\":{\"x\":1},\"constructor\":2}" },
        { "proto-path", "{\"__proto__\": {\"x\": 1}}", ["__proto__", "x"], "1" },
    };

    // case, text, path; the text is not JSON
    public static TheoryData<string, string, string[]> Invalid => new()
    {
        { "trailing-comma-array", "[1, 2,]", [] },
        { "trailing-comma-object", "{\"a\": 1,}", [] },
        { "single-quotes", "{'a': 1}", [] },
        { "unquoted-name", "{a: 1}", [] },
        { "nan", "[NaN]", [] },
        { "infinity", "[Infinity]", [] },
        { "negative-infinity", "-Infinity", [] },
        { "leading-zero", "[01]", [] },
        { "plus-sign", "+1", [] },
        { "hex-number", "0x10", [] },
        { "empty-text", "", [] },
        { "whitespace-only", " \n", [] },
        { "trailing-data", "[1] x", [] },
        { "two-values", "1 2", [] },
        { "comment", "{\"a\": 1} // note", [] },
        { "byte-order-mark", "\uFEFF{\"a\": 1}", [] },
        { "raw-control-char", "[\"a\tb\"]", [] },
        { "bad-escape", "[\"\\x41\"]", [] },
        { "unclosed", "[1, 2", [] },
    };

    // case, text, path; the path names no value
    public static TheoryData<string, string, string[]> NotFound => new()
    {
        { "missing-name", "{\"a\": 1}", ["b"] },
        { "inherited-name", "{\"a\": 1}", ["toString"] },
        { "array-length", "[1, 2]", ["length"] },
        { "index-out-of-range", "[1, 2]", ["2"] },
        { "index-leading-zero", "[1, 2]", ["01"] },
        { "index-negative", "[1, 2]", ["-1"] },
        { "index-plus", "[1, 2]", ["+1"] },
        { "index-non-ascii-digit", "[1, 2]", ["١"] },
        { "through-scalar", "{\"a\": 1}", ["a", "b"] },
        { "through-null", "{\"a\": null}", ["a", "b"] },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void ReturnsCanonicalJson(string name, string text, string[] path, string want)
    {
        Assert.True(want == CanonicalJson.JsonGet(text, path), name);
    }

    [Theory]
    [MemberData(nameof(Invalid))]
    public void RejectsInvalidJson(string name, string text, string[] path)
    {
        Assert.ThrowsAny<JsonException>(() => CanonicalJson.JsonGet(text, path));
        Assert.NotNull(name);
    }

    [Theory]
    [MemberData(nameof(NotFound))]
    public void ReportsMissingValue(string name, string text, string[] path)
    {
        Assert.Throws<KeyNotFoundException>(() => CanonicalJson.JsonGet(text, path));
        Assert.NotNull(name);
    }
}
jsonGet.jsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-json/.

// An array index: ASCII digits, no sign, no leading zero.
const INDEX = /^(?:0|[1-9][0-9]*)$/;

// A JSON number becomes a double, which loses digits above 2**53.
// The reviver reads the source text of each number and makes a BigInt.
function exactIntegers(key, value, context) {
  return typeof value === "number" ? BigInt(context.source) : value;
}

// UTF-8 byte order is code point order. The default sort uses UTF-16 code units.
function byCodePoint(a, b) {
  return Buffer.compare(Buffer.from(a), Buffer.from(b));
}

// Writes the value as canonical JSON. JSON.stringify writes the strings,
// but it cannot write a BigInt, and it keeps the key order of the object,
// where integer-like keys such as "10" come first.
function write(value) {
  if (typeof value === "bigint") return value.toString();
  if (Array.isArray(value)) return `[${value.map(write).join(",")}]`;
  if (value !== null && typeof value === "object") {
    const members = Object.keys(value)
      .sort(byCodePoint)
      .map((key) => `${JSON.stringify(key)}:${write(value[key])}`);
    return `{${members.join(",")}}`;
  }
  return JSON.stringify(value);
}

// Returns the value at path in the JSON text, as canonical JSON.
// Throws a SyntaxError when the text is not JSON.
export function jsonGet(text, path) {
  let value = JSON.parse(text, exactIntegers);
  for (const step of path) {
    if (Array.isArray(value) && INDEX.test(step) && Number(step) < value.length) {
      value = value[Number(step)];
    } else if (value !== null && typeof value === "object" && !Array.isArray(value) && Object.hasOwn(value, step)) {
      value = value[step];
    } else {
      throw new RangeError(`no value at ${JSON.stringify(step)}`);
    }
  }
  return write(value);
}
jsonGet.test.js 95 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-json/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { jsonGet } from "./jsonGet.js";

// [case, text, path, the canonical JSON of the value at path]
const cases = [
  ["member", '{"name": "Ada", "born": 1815}', ["name"], '"Ada"'],
  ["whole-document", '{"b": [1, 2], "a": true}', [], '{"a":true,"b":[1,2]}'],
  ["nested-path", '{"user": {"tags": ["x", "y"]}}', ["user", "tags", "1"], '"y"'],
  ["big-int", '{"id": 9007199254740993}', ["id"], "9007199254740993"],
  ["beyond-int64", "[18446744073709551617, -18446744073709551617]", [], "[18446744073709551617,-18446744073709551617]"],
  ["int64-bounds", "[-9223372036854775808, 9223372036854775807]", [], "[-9223372036854775808,9223372036854775807]"],
  ["negative-zero", "[-0, 0]", [], "[0,0]"],
  ["duplicate-name", '{"a": 1, "a": 2}', ["a"], "2"],
  ["duplicate-name-whole", '{"a": 1, "b": 0, "a": {"c": 3}}', [], '{"a":{"c":3},"b":0}'],
  ["array-index-10", '[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "ten"]', ["10"], '"ten"'],
  ["numeric-name", '{"0": "zero", "1": "one"}', ["0"], '"zero"'],
  ["key-order-ascii", '{"b": 1, "a": 2, "B": 3, "10": 4, "9": 5}', [], '{"10":4,"9":5,"B":3,"a":2,"b":1}'],
  ["key-order-prefix", '{"ab": 1, "a": 2, "": 3}', [], '{"":3,"a":2,"ab":1}'],
  ["key-order-astral", '{"😀": 1, "fi": 2, "é": 3}', [], '{"é":3,"fi":2,"😀":1}'],
  ["non-ascii", '["Zürich", "日本語", "😀"]', [], '["Zürich","日本語","😀"]'],
  ["escaped-non-ascii", '["\\u00e9\\ud83d\\ude00"]', ["0"], '"é😀"'],
  ["escapes", '["q\\" b\\\\ s\\/ t\\t n\\n r\\r"]', [], '["q\\" b\\\\ s/ t\\t n\\n r\\r"]'],
  ["control-chars", '["\\u0000\\u001f\\b\\f\\u007f"]', [], '["\\u0000\\u001f\\b\\f\x7f"]'],
  ["html-chars", '{"html": "<a href=\'x\'>&amp;</a>"}', ["html"], "\"<a href='x'>&amp;</a>\""],
  ["empty-containers", '{"a": {}, "b": [], "c": ""}', [], '{"a":{},"b":[],"c":""}'],
  ["scalar-root", "42", [], "42"],
  ["string-root", '"text"', [], '"text"'],
  ["whitespace", " \n\ttrue\r\n ", [], "true"],
  ["whitespace-inside", '\n{ "a" :\t[ 1 , 2 ] }\r\n', [], '{"a":[1,2]}'],
  ["deep-path", '{"a": [{"b": [[1, {"c": "deep"}]]}]}', ["a", "0", "b", "0", "1", "c"], '"deep"'],
  ["null-member", '{"a": null}', ["a"], "null"],
  ["false-member", '{"a": false, "b": 0}', ["a"], "false"],
  ["proto-name", '{"__proto__": {"x": 1}, "constructor": 2}', [], '{"__proto__":{"x":1},"constructor":2}'],
  ["proto-path", '{"__proto__": {"x": 1}}', ["__proto__", "x"], "1"],
];

// [case, text, path]; the text is not JSON
const invalid = [
  ["trailing-comma-array", "[1, 2,]", []],
  ["trailing-comma-object", '{"a": 1,}', []],
  ["single-quotes", "{'a': 1}", []],
  ["unquoted-name", "{a: 1}", []],
  ["nan", "[NaN]", []],
  ["infinity", "[Infinity]", []],
  ["negative-infinity", "-Infinity", []],
  ["leading-zero", "[01]", []],
  ["plus-sign", "+1", []],
  ["hex-number", "0x10", []],
  ["empty-text", "", []],
  ["whitespace-only", " \n", []],
  ["trailing-data", "[1] x", []],
  ["two-values", "1 2", []],
  ["comment", '{"a": 1} // note', []],
  ["byte-order-mark", '\ufeff{"a": 1}', []],
  ["raw-control-char", '["a\tb"]', []],
  ["bad-escape", '["\\x41"]', []],
  ["unclosed", "[1, 2", []],
];

// [case, text, path]; the path names no value
const notFound = [
  ["missing-name", '{"a": 1}', ["b"]],
  ["inherited-name", '{"a": 1}', ["toString"]],
  ["array-length", "[1, 2]", ["length"]],
  ["index-out-of-range", "[1, 2]", ["2"]],
  ["index-leading-zero", "[1, 2]", ["01"]],
  ["index-negative", "[1, 2]", ["-1"]],
  ["index-plus", "[1, 2]", ["+1"]],
  ["index-non-ascii-digit", "[1, 2]", ["١"]],
  ["through-scalar", '{"a": 1}', ["a", "b"]],
  ["through-null", '{"a": null}', ["a", "b"]],
];

for (const [name, text, path, want] of cases) {
  test(name, () => {
    assert.equal(jsonGet(text, path), want);
  });
}

for (const [name, text, path] of invalid) {
  test(name, () => {
    assert.throws(() => jsonGet(text, path), SyntaxError);
  });
}

for (const [name, text, path] of notFound) {
  test(name, () => {
    assert.throws(() => jsonGet(text, path), RangeError);
  });
}
jsonGet.tsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-json/.

// An array index: ASCII digits, no sign, no leading zero.
const INDEX = /^(?:0|[1-9][0-9]*)$/;

// A JSON number becomes a double, which loses digits above 2**53.
// The reviver reads the source text of each number and makes a BigInt.
function exactIntegers(key: string, value: unknown, context?: { source: string }): unknown {
  return typeof value === "number" && context ? BigInt(context.source) : value;
}

// UTF-8 byte order is code point order. The default sort uses UTF-16 code units.
function byCodePoint(a: string, b: string): number {
  return Buffer.compare(Buffer.from(a), Buffer.from(b));
}

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

// Writes the value as canonical JSON. JSON.stringify writes the strings,
// but it cannot write a BigInt, and it keeps the key order of the object,
// where integer-like keys such as "10" come first.
function write(value: unknown): string {
  if (typeof value === "bigint") return value.toString();
  if (Array.isArray(value)) return `[${value.map(write).join(",")}]`;
  if (isObject(value)) {
    const members = Object.keys(value)
      .sort(byCodePoint)
      .map((key) => `${JSON.stringify(key)}:${write(value[key])}`);
    return `{${members.join(",")}}`;
  }
  return JSON.stringify(value);
}

// Returns the value at path in the JSON text, as canonical JSON.
// Throws a SyntaxError when the text is not JSON.
export function jsonGet(text: string, path: readonly string[]): string {
  let value: unknown = JSON.parse(text, exactIntegers);
  for (const step of path) {
    if (Array.isArray(value) && INDEX.test(step) && Number(step) < value.length) {
      value = value[Number(step)];
    } else if (isObject(value) && Object.hasOwn(value, step)) {
      value = value[step];
    } else {
      throw new RangeError(`no value at ${JSON.stringify(step)}`);
    }
  }
  return write(value);
}
jsonGet.test.ts 95 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-json/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { jsonGet } from "./jsonGet.ts";

// [case, text, path, the canonical JSON of the value at path]
const cases: [string, string, string[], string][] = [
  ["member", '{"name": "Ada", "born": 1815}', ["name"], '"Ada"'],
  ["whole-document", '{"b": [1, 2], "a": true}', [], '{"a":true,"b":[1,2]}'],
  ["nested-path", '{"user": {"tags": ["x", "y"]}}', ["user", "tags", "1"], '"y"'],
  ["big-int", '{"id": 9007199254740993}', ["id"], "9007199254740993"],
  ["beyond-int64", "[18446744073709551617, -18446744073709551617]", [], "[18446744073709551617,-18446744073709551617]"],
  ["int64-bounds", "[-9223372036854775808, 9223372036854775807]", [], "[-9223372036854775808,9223372036854775807]"],
  ["negative-zero", "[-0, 0]", [], "[0,0]"],
  ["duplicate-name", '{"a": 1, "a": 2}', ["a"], "2"],
  ["duplicate-name-whole", '{"a": 1, "b": 0, "a": {"c": 3}}', [], '{"a":{"c":3},"b":0}'],
  ["array-index-10", '[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "ten"]', ["10"], '"ten"'],
  ["numeric-name", '{"0": "zero", "1": "one"}', ["0"], '"zero"'],
  ["key-order-ascii", '{"b": 1, "a": 2, "B": 3, "10": 4, "9": 5}', [], '{"10":4,"9":5,"B":3,"a":2,"b":1}'],
  ["key-order-prefix", '{"ab": 1, "a": 2, "": 3}', [], '{"":3,"a":2,"ab":1}'],
  ["key-order-astral", '{"😀": 1, "fi": 2, "é": 3}', [], '{"é":3,"fi":2,"😀":1}'],
  ["non-ascii", '["Zürich", "日本語", "😀"]', [], '["Zürich","日本語","😀"]'],
  ["escaped-non-ascii", '["\\u00e9\\ud83d\\ude00"]', ["0"], '"é😀"'],
  ["escapes", '["q\\" b\\\\ s\\/ t\\t n\\n r\\r"]', [], '["q\\" b\\\\ s/ t\\t n\\n r\\r"]'],
  ["control-chars", '["\\u0000\\u001f\\b\\f\\u007f"]', [], '["\\u0000\\u001f\\b\\f\x7f"]'],
  ["html-chars", '{"html": "<a href=\'x\'>&amp;</a>"}', ["html"], "\"<a href='x'>&amp;</a>\""],
  ["empty-containers", '{"a": {}, "b": [], "c": ""}', [], '{"a":{},"b":[],"c":""}'],
  ["scalar-root", "42", [], "42"],
  ["string-root", '"text"', [], '"text"'],
  ["whitespace", " \n\ttrue\r\n ", [], "true"],
  ["whitespace-inside", '\n{ "a" :\t[ 1 , 2 ] }\r\n', [], '{"a":[1,2]}'],
  ["deep-path", '{"a": [{"b": [[1, {"c": "deep"}]]}]}', ["a", "0", "b", "0", "1", "c"], '"deep"'],
  ["null-member", '{"a": null}', ["a"], "null"],
  ["false-member", '{"a": false, "b": 0}', ["a"], "false"],
  ["proto-name", '{"__proto__": {"x": 1}, "constructor": 2}', [], '{"__proto__":{"x":1},"constructor":2}'],
  ["proto-path", '{"__proto__": {"x": 1}}', ["__proto__", "x"], "1"],
];

// [case, text, path]; the text is not JSON
const invalid: [string, string, string[]][] = [
  ["trailing-comma-array", "[1, 2,]", []],
  ["trailing-comma-object", '{"a": 1,}', []],
  ["single-quotes", "{'a': 1}", []],
  ["unquoted-name", "{a: 1}", []],
  ["nan", "[NaN]", []],
  ["infinity", "[Infinity]", []],
  ["negative-infinity", "-Infinity", []],
  ["leading-zero", "[01]", []],
  ["plus-sign", "+1", []],
  ["hex-number", "0x10", []],
  ["empty-text", "", []],
  ["whitespace-only", " \n", []],
  ["trailing-data", "[1] x", []],
  ["two-values", "1 2", []],
  ["comment", '{"a": 1} // note', []],
  ["byte-order-mark", '\ufeff{"a": 1}', []],
  ["raw-control-char", '["a\tb"]', []],
  ["bad-escape", '["\\x41"]', []],
  ["unclosed", "[1, 2", []],
];

// [case, text, path]; the path names no value
const notFound: [string, string, string[]][] = [
  ["missing-name", '{"a": 1}', ["b"]],
  ["inherited-name", '{"a": 1}', ["toString"]],
  ["array-length", "[1, 2]", ["length"]],
  ["index-out-of-range", "[1, 2]", ["2"]],
  ["index-leading-zero", "[1, 2]", ["01"]],
  ["index-negative", "[1, 2]", ["-1"]],
  ["index-plus", "[1, 2]", ["+1"]],
  ["index-non-ascii-digit", "[1, 2]", ["١"]],
  ["through-scalar", '{"a": 1}', ["a", "b"]],
  ["through-null", '{"a": null}', ["a", "b"]],
];

for (const [name, text, path, want] of cases) {
  test(name, () => {
    assert.equal(jsonGet(text, path), want);
  });
}

for (const [name, text, path] of invalid) {
  test(name, () => {
    assert.throws(() => jsonGet(text, path), SyntaxError);
  });
}

for (const [name, text, path] of notFound) {
  test(name, () => {
    assert.throws(() => jsonGet(text, path), RangeError);
  });
}
json_get.goI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-json/.

// Package jsonget reads a value from a JSON text and writes it back as canonical JSON.
package jsonget

import (
	"bytes"
	"encoding/json"
	"errors"
	"io"
	"regexp"
	"strconv"
	"strings"
)

// ErrNotFound is the error when the path names no value.
var ErrNotFound = errors.New("no value at the path")

// An array index: ASCII digits, no sign, no leading zero.
var index = regexp.MustCompile(`^(?:0|[1-9][0-9]*)$`)

// JSONGet returns the value at path in the JSON text, as canonical JSON.
func JSONGet(text string, path []string) (string, error) {
	dec := json.NewDecoder(strings.NewReader(text))
	// Keep each number as its text (json.Number), not as a float64.
	dec.UseNumber()
	var value any
	if err := dec.Decode(&value); err != nil {
		if err == io.EOF {
			return "", io.ErrUnexpectedEOF // the text holds no value
		}
		return "", err
	}
	// Decode stops after one value. Only white space may follow it.
	if _, err := dec.Token(); err != io.EOF {
		return "", errors.New("data after the JSON value")
	}
	for _, step := range path {
		switch v := value.(type) {
		case map[string]any:
			next, ok := v[step]
			if !ok {
				return "", ErrNotFound
			}
			value = next
		case []any:
			i, err := strconv.Atoi(step)
			if !index.MatchString(step) || err != nil || i >= len(v) {
				return "", ErrNotFound
			}
			value = v[i]
		default:
			return "", ErrNotFound
		}
	}
	var out bytes.Buffer
	enc := json.NewEncoder(&out)
	// Without this, the encoder writes <, > and & as \u003c, \u003e and \u0026.
	enc.SetEscapeHTML(false)
	// The encoder sorts the keys of a map by their bytes, which is code point order.
	if err := enc.Encode(normalize(value)); err != nil {
		return "", err
	}
	return strings.TrimSuffix(out.String(), "\n"), nil
}

// normalize writes -0 as 0. A json.Number keeps the text of the number as it is.
func normalize(value any) any {
	switch v := value.(type) {
	case map[string]any:
		for k, e := range v {
			v[k] = normalize(e)
		}
	case []any:
		for i, e := range v {
			v[i] = normalize(e)
		}
	case json.Number:
		if v == "-0" {
			return json.Number("0")
		}
	}
	return value
}
json_get_test.go 117 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-and-write-json/.

package jsonget

import (
	"errors"
	"testing"
)

type errorCase struct {
	name, text string
	path       []string
}

func TestCases(t *testing.T) {
	cases := []struct {
		name, text string
		path       []string
		want       string
	}{
		{"member", "{\"name\": \"Ada\", \"born\": 1815}", []string{"name"}, "\"Ada\""},
		{"whole-document", "{\"b\": [1, 2], \"a\": true}", nil, "{\"a\":true,\"b\":[1,2]}"},
		{"nested-path", "{\"user\": {\"tags\": [\"x\", \"y\"]}}", []string{"user", "tags", "1"}, "\"y\""},
		{"big-int", "{\"id\": 9007199254740993}", []string{"id"}, "9007199254740993"},
		{"beyond-int64", "[18446744073709551617, -18446744073709551617]", nil, "[18446744073709551617,-18446744073709551617]"},
		{"int64-bounds", "[-9223372036854775808, 9223372036854775807]", nil, "[-9223372036854775808,9223372036854775807]"},
		{"negative-zero", "[-0, 0]", nil, "[0,0]"},
		{"duplicate-name", "{\"a\": 1, \"a\": 2}", []string{"a"}, "2"},
		{"duplicate-name-whole", "{\"a\": 1, \"b\": 0, \"a\": {\"c\": 3}}", nil, "{\"a\":{\"c\":3},\"b\":0}"},
		{"array-index-10", "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, \"ten\"]", []string{"10"}, "\"ten\""},
		{"numeric-name", "{\"0\": \"zero\", \"1\": \"one\"}", []string{"0"}, "\"zero\""},
		{"key-order-ascii", "{\"b\": 1, \"a\": 2, \"B\": 3, \"10\": 4, \"9\": 5}", nil, "{\"10\":4,\"9\":5,\"B\":3,\"a\":2,\"b\":1}"},
		{"key-order-prefix", "{\"ab\": 1, \"a\": 2, \"\": 3}", nil, "{\"\":3,\"a\":2,\"ab\":1}"},
		{"key-order-astral", "{\"😀\": 1, \"fi\": 2, \"é\": 3}", nil, "{\"é\":3,\"fi\":2,\"😀\":1}"},
		{"non-ascii", "[\"Zürich\", \"日本語\", \"😀\"]", nil, "[\"Zürich\",\"日本語\",\"😀\"]"},
		{"escaped-non-ascii", "[\"\\u00e9\\ud83d\\ude00\"]", []string{"0"}, "\"é😀\""},
		{"escapes", "[\"q\\\" b\\\\ s\\/ t\\t n\\n r\\r\"]", nil, "[\"q\\\" b\\\\ s/ t\\t n\\n r\\r\"]"},
		{"control-chars", "[\"\\u0000\\u001f\\b\\f\\u007f\"]", nil, "[\"\\u0000\\u001f\\b\\f\x7f\"]"},
		{"html-chars", "{\"html\": \"<a href='x'>&amp;</a>\"}", []string{"html"}, "\"<a href='x'>&amp;</a>\""},
		{"empty-containers", "{\"a\": {}, \"b\": [], \"c\": \"\"}", nil, "{\"a\":{},\"b\":[],\"c\":\"\"}"},
		{"scalar-root", "42", nil, "42"},
		{"string-root", "\"text\"", nil, "\"text\""},
		{"whitespace", " \n\ttrue\r\n ", nil, "true"},
		{"whitespace-inside", "\n{ \"a\" :\t[ 1 , 2 ] }\r\n", nil, "{\"a\":[1,2]}"},
		{"deep-path", "{\"a\": [{\"b\": [[1, {\"c\": \"deep\"}]]}]}", []string{"a", "0", "b", "0", "1", "c"}, "\"deep\""},
		{"null-member", "{\"a\": null}", []string{"a"}, "null"},
		{"false-member", "{\"a\": false, \"b\": 0}", []string{"a"}, "false"},
		{"proto-name", "{\"__proto__\": {\"x\": 1}, \"constructor\": 2}", nil, "{\"__proto__\":{\"x\":1},\"constructor\":2}"},
		{"proto-path", "{\"__proto__\": {\"x\": 1}}", []string{"__proto__", "x"}, "1"},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			got, err := JSONGet(c.text, c.path)
			if err != nil {
				t.Fatal(err)
			}
			if got != c.want {
				t.Errorf("got %q, want %q", got, c.want)
			}
		})
	}
}

func TestInvalidJSON(t *testing.T) {
	cases := []errorCase{
		{"trailing-comma-array", "[1, 2,]", nil},
		{"trailing-comma-object", "{\"a\": 1,}", nil},
		{"single-quotes", "{'a': 1}", nil},
		{"unquoted-name", "{a: 1}", nil},
		{"nan", "[NaN]", nil},
		{"infinity", "[Infinity]", nil},
		{"negative-infinity", "-Infinity", nil},
		{"leading-zero", "[01]", nil},
		{"plus-sign", "+1", nil},
		{"hex-number", "0x10", nil},
		{"empty-text", "", nil},
		{"whitespace-only", " \n", nil},
		{"trailing-data", "[1] x", nil},
		{"two-values", "1 2", nil},
		{"comment", "{\"a\": 1} // note", nil},
		{"byte-order-mark", "\ufeff{\"a\": 1}", nil},
		{"raw-control-char", "[\"a\tb\"]", nil},
		{"bad-escape", "[\"\\x41\"]", nil},
		{"unclosed", "[1, 2", nil},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			_, err := JSONGet(c.text, c.path)
			if err == nil || errors.Is(err, ErrNotFound) {
				t.Errorf("got error %v, want a syntax error", err)
			}
		})
	}
}

func TestNotFound(t *testing.T) {
	cases := []errorCase{
		{"missing-name", "{\"a\": 1}", []string{"b"}},
		{"inherited-name", "{\"a\": 1}", []string{"toString"}},
		{"array-length", "[1, 2]", []string{"length"}},
		{"index-out-of-range", "[1, 2]", []string{"2"}},
		{"index-leading-zero", "[1, 2]", []string{"01"}},
		{"index-negative", "[1, 2]", []string{"-1"}},
		{"index-plus", "[1, 2]", []string{"+1"}},
		{"index-non-ascii-digit", "[1, 2]", []string{"١"}},
		{"through-scalar", "{\"a\": 1}", []string{"a", "b"}},
		{"through-null", "{\"a\": null}", []string{"a", "b"}},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			if _, err := JSONGet(c.text, c.path); !errors.Is(err, ErrNotFound) {
				t.Errorf("got error %v, want ErrNotFound", err)
			}
		})
	}
}

References

  1. T. Bray (Ed.), RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format, December 2017, 2 JSON Grammar; 4 Objects; 6 Numbers; 7 Strings; 8.1 Character Encoding; 8.2 Unicode Characters; 9 Parsers
  2. P. Bryan (Ed.), K. Zyp, M. Nottingham (Ed.), RFC 6901: JavaScript Object Notation (JSON) Pointer, April 2013, 4 Evaluation, array-index
  3. A. Rundgren, B. Jordan, S. Erdtman, RFC 8785: JSON Canonicalization Scheme (JCS), June 2020, 3.2.2.2 Serialization of Strings; 3.2.3 Sorting of Object Properties
  4. The Python Standard Library, json, Python 3.14, json.dumps (ensure_ascii, allow_nan, separators, sort_keys); json.loads (parse_constant, object_pairs_hook); JSONDecodeError; Standard Compliance and Interoperability
  5. The Python Standard Library, Built-in Types, Python 3.14, Integer string conversion length limitation
  6. ECMA-262, ECMAScript 2026 Language Specification, 25.5 The JSON Object (JSON.parse, JSON.stringify); OrdinaryOwnPropertyKeys
  7. TC39 proposal, JSON.parse source text access, the README, the context argument of the reviver
  8. Node.js documentation, Buffer, Buffer.compare(buf1, buf2)
  9. Go standard library, package encoding/json, func Marshal; func Unmarshal; Decoder.Decode; Decoder.UseNumber; Encoder.SetEscapeHTML; SyntaxError
  10. .NET API reference, JsonDocument, Parse(String, JsonDocumentOptions), Exceptions
  11. .NET API reference, JsonDocumentOptions, AllowDuplicateProperties; AllowTrailingCommas; CommentHandling; MaxDepth
  12. .NET documentation, How to customize character encoding with System.Text.Json, the default encoder, UnsafeRelaxedJsonEscaping

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
  • no problem that the node solves has a contract with shared cases (09.2)
Code (go)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (javascript)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (python)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (typescript)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source

The native tests pass in 5 of 5 languages in this build.