Taskintro
Pretty-print JSON
Also called format JSON, indent JSON, beautify JSON, JSON pretty printer.
Parse a JSON text and write it back with one member or element on each line, an indent of two spaces for each level, and the names of each object sorted, so the output is the same for the same data.
- Evidence
- Code in 5 languages
Task
Parse a JSON text and write the same value back as a text that a person can read. Each solution is a function pretty_json(text) that returns the new text.
JSON allows white space between all tokens: "Insignificant whitespace is allowed before or after any of the six structural characters"1. A pretty printer uses this freedom in one fixed way:
- Each element of an array and each member of an object is on its own line, with two more spaces of indent than its container. The closing
]or}is on its own line. - An empty array is
[]and an empty object is{}. - A name is followed by
:, and a line ends with,when another item follows. - The members of each object are sorted by name in code point order, and the last member of a repeated name wins.
- Integers keep all their digits,
-0becomes0, and strings use the escapes of the page Read and write JSON. Non-ASCII characters are written as themselves. - The output has no line break at the end.
With sorted names, two texts with the same data give the same output, so a diff of two files shows only the changes in the data. The output is also a valid input: a second run gives the same text.
The solution reports invalid-json when the text is not a JSON text. The contract has the same limits as Read and write JSON: the numbers are integers, and no string holds an unpaired surrogate, U+2028 or U+2029.
Solutions
The standard libraries of Java, Rust, C, C++ and Bash have no JSON parser, so this page has no solution in those languages. matrix.yaml names the usual libraries. On the command line, jq . pretty-prints its input: the jq manual says that the main use of the program . "is to validate and pretty-print the inputs"2. Add --sort-keys to sort the names, and --indent n for another indent2.
- Python.
json.dumpsdoes all the work. Withindent=2, "JSON array elements and object members will be pretty-printed with that indent level"3, and withsort_keys=True"the output of dictionaries will be sorted by key"3.ensure_ascii=Falsekeeps non-ASCII characters, and aparse_constanthook rejectsNaNandInfinity. From a shell,python -m jsondoes the same job3. - JavaScript and TypeScript (Node.js).
JSON.stringify(value, null, 2)indents, because a number forspace"indicates the number of space characters to be used as indentation"4. But it keeps the key order of the object and it cannot write aBigInt, so the solution has a shortwritefunction that indents arrays and objects and callsJSON.stringifyfor each string. The reviver readscontext.source, "The original JSON string representing this value"5, to keep the digits of large integers. - C#.
JsonSerializerOptions.WriteIndentedpretty-prints6, but "By default, the serializer escapes all non-ASCII characters"7. The solution reads the text withJsonDocument, which keeps each number as its source text, and writes the indented text with aStringBuilder. - Go. An
EncoderwithSetEscapeHTML(false)andSetIndentwith an indent of two spaces writes the value. A decoder withUseNumberkeeps each number as its text. The encoder sorts maps: "The map keys are sorted and used as JSON object keys"8.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl. Each case gives the text and the pretty output, and each test also checks that a second run gives the same text.
key-order-ascii,key-order-prefix,key-order-astralandkey-order-nested:"10"sorts before"9",""comes first,"fi"(U+FB01) sorts before"😀"(U+1F600), and the names of nested objects are sorted too.duplicate-name:{"a": 1, "b": 0, "a": {"c": 3}}has one member"a"with the value{"c": 3}.big-int,beyond-int64andnegative-zero: 9007199254740993 and ±18446744073709551617 keep all their digits, and-0becomes0.non-ascii,escaped-non-ascii,escapes,control-charsandhtml-chars: the escape\u00e9becomesé,\/becomes/, U+001F stays escaped, and<,>and&stay as they are.empty-containers,empty-object-rootandempty-array-root:{}and[]stay on one line, also when the input is[ ].scalar-root,string-rootandliterals: a number, a string,true,falseandnullhave no indent.compact-input,whitespace-insideandalready-pretty: the white space of the input has no effect on the output.deep:[[[1](/languages/all/#1)]]has five lines of indent.
cases/errors.jsonl lists the texts that are not JSON, as in Read and write JSON. The toolchain does not load this file yet, so each test file holds these cases by name.
Pitfalls
- Python escapes non-ASCII and keeps the input order by default.
ensure_asciiis true by default, andsort_keysis false:
import json
value = json.loads('{"name": "Zürich", "id": 2, "area": 88}')
print(json.dumps(value, indent=2))
print(json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False))
{
"name": "Z\u00fcrich",
"id": 2,
"area": 88
}
{
"area": 88,
"id": 2,
"name": "Zürich"
}
JSON.stringifydoes not keep the order or the digits. A JavaScript object lists integer-like names first in numeric order, then the other names in insertion order, and a large integer becomes a double:
This code runs but gives a wrong answer on purpose.
const value = JSON.parse('{"b": 1, "a": 2, "10": 3, "9": 4, "id": 9007199254740993}');
console.log(JSON.stringify(value, null, 2));
{
"9": 4,
"10": 3,
"b": 1,
"a": 2,
"id": 9007199254740992
}
- Go escapes HTML characters.
json.MarshalIndentwrites<,>and&as\u003c,\u003eand\u0026. The output is valid JSON but harder to read. Use anEncoderwithSetEscapeHTML(false):
package main
import (
"encoding/json"
"fmt"
"os"
)
func main() {
value := map[string]string{"html": "<b>Tom & Jerry</b>"}
out, _ := json.MarshalIndent(value, "", " ")
fmt.Println(string(out))
enc := json.NewEncoder(os.Stdout)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
enc.Encode(value)
}
{
"html": "\u003cb\u003eTom \u0026 Jerry\u003c/b\u003e"
}
{
"html": "<b>Tom & Jerry</b>"
}
- Pretty-printing changes the bytes. A hash or a signature of the original text does not match the pretty text. Compute it on the original bytes, or on a canonical form, see Read and write JSON.
- A tool adds a line break. The command-line tools jq and
python -m jsonend their output with a line break. The solutions on this page do not, because a function returns a value, not a file.
Related tasks
- Read and write JSON parses JSON, gets one value and writes it back in a compact canonical form.
- Stream-parse a large JSON file reads a JSON text that does not fit in memory.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/pretty-print-json/.
import json
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 pretty_json(text: str) -> str:
"""Returns the JSON text indented by two spaces, with the names of each object sorted."""
value = json.loads(text, parse_constant=reject_constant)
# With indent, the separators are "," at the end of a line and ": " after a name.
return json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False, allow_nan=False)
test_pretty_json.py 165 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/pretty-print-json/.
import json
import pytest
from pretty_json import pretty_json
# name: (text, the pretty text)
CASES = {
"object": (
"{\"name\": \"Ada\", \"born\": 1815, \"tags\": [\"math\", \"code\"]}",
"{\n \"born\": 1815,\n \"name\": \"Ada\",\n \"tags\": [\n \"math\",\n \"code\"\n ]\n}",
),
"nested": (
"{\"user\": {\"id\": 7, \"roles\": [\"admin\"]}, \"ok\": true}",
"{\n \"ok\": true,\n \"user\": {\n \"id\": 7,\n \"roles\": [\n \"admin\"\n ]\n }\n}",
),
"array-of-objects": (
"[{\"a\": 1}, {\"b\": null}]",
"[\n {\n \"a\": 1\n },\n {\n \"b\": null\n }\n]",
),
"compact-input": (
"{\"a\":[1,2,{\"b\":false}]}",
"{\n \"a\": [\n 1,\n 2,\n {\n \"b\": false\n }\n ]\n}",
),
"key-order-ascii": (
"{\"b\": 1, \"a\": 2, \"B\": 3, \"10\": 4, \"9\": 5}",
"{\n \"10\": 4,\n \"9\": 5,\n \"B\": 3,\n \"a\": 2,\n \"b\": 1\n}",
),
"key-order-prefix": (
"{\"ab\": 1, \"a\": 2, \"\": 3}",
"{\n \"\": 3,\n \"a\": 2,\n \"ab\": 1\n}",
),
"key-order-astral": (
"{\"😀\": 1, \"fi\": 2, \"é\": 3}",
"{\n \"é\": 3,\n \"fi\": 2,\n \"😀\": 1\n}",
),
"key-order-nested": (
"{\"z\": {\"y\": 1, \"x\": 2}, \"a\": [{\"d\": 1, \"c\": 2}]}",
"{\n \"a\": [\n {\n \"c\": 2,\n \"d\": 1\n }\n ],\n \"z\": {\n \"x\": 2,\n \"y\": 1\n }\n}",
),
"duplicate-name": (
"{\"a\": 1, \"b\": 0, \"a\": {\"c\": 3}}",
"{\n \"a\": {\n \"c\": 3\n },\n \"b\": 0\n}",
),
"big-int": (
"{\"id\": 9007199254740993}",
"{\n \"id\": 9007199254740993\n}",
),
"beyond-int64": (
"[18446744073709551617, -18446744073709551617]",
"[\n 18446744073709551617,\n -18446744073709551617\n]",
),
"negative-zero": (
"[-0, 0]",
"[\n 0,\n 0\n]",
),
"non-ascii": (
"[\"Zürich\", \"日本語\", \"😀\"]",
"[\n \"Zürich\",\n \"日本語\",\n \"😀\"\n]",
),
"escaped-non-ascii": (
"[\"\\u00e9\\ud83d\\ude00\"]",
"[\n \"é😀\"\n]",
),
"escapes": (
"[\"q\\\" b\\\\ s\\/ t\\t n\\n r\\r\"]",
"[\n \"q\\\" b\\\\ s/ t\\t n\\n r\\r\"\n]",
),
"control-chars": (
"[\"\\u0000\\u001f\\b\\f\\u007f\"]",
"[\n \"\\u0000\\u001f\\b\\f\x7f\"\n]",
),
"html-chars": (
"{\"html\": \"<a href='x'>&</a>\"}",
"{\n \"html\": \"<a href='x'>&</a>\"\n}",
),
"empty-containers": (
"{\"a\": {}, \"b\": [], \"c\": \"\"}",
"{\n \"a\": {},\n \"b\": [],\n \"c\": \"\"\n}",
),
"empty-object-root": (
"{}",
"{}",
),
"empty-array-root": (
"[ ]",
"[]",
),
"scalar-root": (
"42",
"42",
),
"string-root": (
"\"text\"",
"\"text\"",
),
"literals": (
"[true, false, null]",
"[\n true,\n false,\n null\n]",
),
"whitespace-inside": (
"\n{ \"a\" :\t[ 1 , 2 ] }\r\n",
"{\n \"a\": [\n 1,\n 2\n ]\n}",
),
"already-pretty": (
"{\n \"a\": [\n 1,\n 2\n ],\n \"b\": {}\n}",
"{\n \"a\": [\n 1,\n 2\n ],\n \"b\": {}\n}",
),
"deep": (
"[[[[1]]]]",
"[\n [\n [\n [\n 1\n ]\n ]\n ]\n]",
),
}
# name: text that 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",
"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",
}
@pytest.mark.parametrize("name", CASES)
def test_cases(name: str) -> None:
text, want = CASES[name]
assert pretty_json(text) == want
@pytest.mark.parametrize("name", CASES)
def test_idempotent(name: str) -> None:
# The output is a JSON text, and pretty-printing it again gives the same text.
want = CASES[name][1]
assert pretty_json(want) == want
@pytest.mark.parametrize("name", INVALID)
def test_invalid_json(name: str) -> None:
with pytest.raises(ValueError):
pretty_json(INVALID[name])
def test_decode_error_position() -> None:
# JSONDecodeError is a subclass of ValueError. It gives the line and column of the error.
# The column depends on the Python version: 3.14 gives the comma (6) and 3.12 gives the ] (7).
with pytest.raises(json.JSONDecodeError) as info:
pretty_json("[1, 2,]")
assert info.value.lineno == 1 and info.value.colno in (6, 7)
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pretty-print-json/.
using System.Text;
using System.Text.Json;
public static class PrettyJson
{
// Returns the JSON text indented by two spaces, with the names of each object sorted.
// Throws a JsonException when the text is not JSON.
public static string Format(string text)
{
// JsonDocument keeps each number as its text, so no digit is lost.
using JsonDocument document = JsonDocument.Parse(text);
var output = new StringBuilder();
Write(document.RootElement, "", output);
return output.ToString();
}
// 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 with an indent of two spaces for each level. The encoders of
// System.Text.Json escape non-ASCII characters, so this writer escapes the strings itself.
private static void Write(JsonElement value, string indent, StringBuilder output)
{
string inner = indent + " ";
switch (value.ValueKind)
{
case JsonValueKind.Object:
// JsonDocument keeps every member of a repeated name. The last one wins.
var members = new Dictionary<string, JsonElement>();
foreach (JsonProperty member in value.EnumerateObject())
{
members[member.Name] = member.Value;
}
if (members.Count == 0)
{
output.Append("{}");
break;
}
var names = members.Keys.ToList();
names.Sort(ByCodePoint);
output.Append('{');
for (int i = 0; i < names.Count; i++)
{
output.Append(i > 0 ? ",\n" : "\n").Append(inner);
WriteString(names[i], output);
output.Append(": ");
Write(members[names[i]], inner, output);
}
output.Append('\n').Append(indent).Append('}');
break;
case JsonValueKind.Array:
if (value.GetArrayLength() == 0)
{
output.Append("[]");
break;
}
output.Append('[');
int n = 0;
foreach (JsonElement element in value.EnumerateArray())
{
output.Append(n++ > 0 ? ",\n" : "\n").Append(inner);
Write(element, inner, output);
}
output.Append('\n').Append(indent).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('"');
}
}
PrettyJsonTests.cs 79 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pretty-print-json/.
using System.Text.Json;
using Xunit;
public sealed class PrettyJsonTests
{
// case, text, the pretty text
public static TheoryData<string, string, string> Cases => new()
{
{ "object", "{\"name\": \"Ada\", \"born\": 1815, \"tags\": [\"math\", \"code\"]}", "{\n \"born\": 1815,\n \"name\": \"Ada\",\n \"tags\": [\n \"math\",\n \"code\"\n ]\n}" },
{ "nested", "{\"user\": {\"id\": 7, \"roles\": [\"admin\"]}, \"ok\": true}", "{\n \"ok\": true,\n \"user\": {\n \"id\": 7,\n \"roles\": [\n \"admin\"\n ]\n }\n}" },
{ "array-of-objects", "[{\"a\": 1}, {\"b\": null}]", "[\n {\n \"a\": 1\n },\n {\n \"b\": null\n }\n]" },
{ "compact-input", "{\"a\":[1,2,{\"b\":false}]}", "{\n \"a\": [\n 1,\n 2,\n {\n \"b\": false\n }\n ]\n}" },
{ "key-order-ascii", "{\"b\": 1, \"a\": 2, \"B\": 3, \"10\": 4, \"9\": 5}", "{\n \"10\": 4,\n \"9\": 5,\n \"B\": 3,\n \"a\": 2,\n \"b\": 1\n}" },
{ "key-order-prefix", "{\"ab\": 1, \"a\": 2, \"\": 3}", "{\n \"\": 3,\n \"a\": 2,\n \"ab\": 1\n}" },
{ "key-order-astral", "{\"😀\": 1, \"fi\": 2, \"é\": 3}", "{\n \"é\": 3,\n \"fi\": 2,\n \"😀\": 1\n}" },
{ "key-order-nested", "{\"z\": {\"y\": 1, \"x\": 2}, \"a\": [{\"d\": 1, \"c\": 2}]}", "{\n \"a\": [\n {\n \"c\": 2,\n \"d\": 1\n }\n ],\n \"z\": {\n \"x\": 2,\n \"y\": 1\n }\n}" },
{ "duplicate-name", "{\"a\": 1, \"b\": 0, \"a\": {\"c\": 3}}", "{\n \"a\": {\n \"c\": 3\n },\n \"b\": 0\n}" },
{ "big-int", "{\"id\": 9007199254740993}", "{\n \"id\": 9007199254740993\n}" },
{ "beyond-int64", "[18446744073709551617, -18446744073709551617]", "[\n 18446744073709551617,\n -18446744073709551617\n]" },
{ "negative-zero", "[-0, 0]", "[\n 0,\n 0\n]" },
{ "non-ascii", "[\"Zürich\", \"日本語\", \"😀\"]", "[\n \"Zürich\",\n \"日本語\",\n \"😀\"\n]" },
{ "escaped-non-ascii", "[\"\\u00e9\\ud83d\\ude00\"]", "[\n \"é😀\"\n]" },
{ "escapes", "[\"q\\\" b\\\\ s\\/ t\\t n\\n r\\r\"]", "[\n \"q\\\" b\\\\ s/ t\\t n\\n r\\r\"\n]" },
{ "control-chars", "[\"\\u0000\\u001f\\b\\f\\u007f\"]", "[\n \"\\u0000\\u001f\\b\\f\u007f\"\n]" },
{ "html-chars", "{\"html\": \"<a href='x'>&</a>\"}", "{\n \"html\": \"<a href='x'>&</a>\"\n}" },
{ "empty-containers", "{\"a\": {}, \"b\": [], \"c\": \"\"}", "{\n \"a\": {},\n \"b\": [],\n \"c\": \"\"\n}" },
{ "empty-object-root", "{}", "{}" },
{ "empty-array-root", "[ ]", "[]" },
{ "scalar-root", "42", "42" },
{ "string-root", "\"text\"", "\"text\"" },
{ "literals", "[true, false, null]", "[\n true,\n false,\n null\n]" },
{ "whitespace-inside", "\n{ \"a\" :\t[ 1 , 2 ] }\r\n", "{\n \"a\": [\n 1,\n 2\n ]\n}" },
{ "already-pretty", "{\n \"a\": [\n 1,\n 2\n ],\n \"b\": {}\n}", "{\n \"a\": [\n 1,\n 2\n ],\n \"b\": {}\n}" },
{ "deep", "[[[[1]]]]", "[\n [\n [\n [\n 1\n ]\n ]\n ]\n]" },
};
// case, text that is not JSON
public static TheoryData<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" },
{ "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" },
};
[Theory]
[MemberData(nameof(Cases))]
public void WritesPrettyJson(string name, string text, string want)
{
Assert.True(want == PrettyJson.Format(text), name);
// Pretty-printing the output again gives the same text.
Assert.True(want == PrettyJson.Format(want), name);
}
[Theory]
[MemberData(nameof(Invalid))]
public void RejectsInvalidJson(string name, string text)
{
Assert.ThrowsAny<JsonException>(() => PrettyJson.Format(text));
Assert.NotNull(name);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pretty-print-json/.
// 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));
}
// JSON.stringify(value, null, 2) cannot write a BigInt, and it keeps the
// key order of the object, where integer-like keys such as "10" come first.
// So this function writes the arrays and objects, and JSON.stringify writes the strings.
function write(value, indent) {
const inner = indent + " ";
if (typeof value === "bigint") return value.toString();
if (Array.isArray(value)) {
if (value.length === 0) return "[]";
const items = value.map((item) => inner + write(item, inner));
return `[\n${items.join(",\n")}\n${indent}]`;
}
if (value !== null && typeof value === "object") {
const keys = Object.keys(value).sort(byCodePoint);
if (keys.length === 0) return "{}";
const members = keys.map((key) => `${inner}${JSON.stringify(key)}: ${write(value[key], inner)}`);
return `{\n${members.join(",\n")}\n${indent}}`;
}
return JSON.stringify(value);
}
// Returns the JSON text indented by two spaces, with the names of each object sorted.
// Throws a SyntaxError when the text is not JSON.
export function prettyJson(text) {
return write(JSON.parse(text, exactIntegers), "");
}
prettyJson.test.js 73 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pretty-print-json/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { prettyJson } from "./prettyJson.js";
// [case, text, the pretty text]
const cases = [
["object", "{\"name\": \"Ada\", \"born\": 1815, \"tags\": [\"math\", \"code\"]}", "{\n \"born\": 1815,\n \"name\": \"Ada\",\n \"tags\": [\n \"math\",\n \"code\"\n ]\n}"],
["nested", "{\"user\": {\"id\": 7, \"roles\": [\"admin\"]}, \"ok\": true}", "{\n \"ok\": true,\n \"user\": {\n \"id\": 7,\n \"roles\": [\n \"admin\"\n ]\n }\n}"],
["array-of-objects", "[{\"a\": 1}, {\"b\": null}]", "[\n {\n \"a\": 1\n },\n {\n \"b\": null\n }\n]"],
["compact-input", "{\"a\":[1,2,{\"b\":false}]}", "{\n \"a\": [\n 1,\n 2,\n {\n \"b\": false\n }\n ]\n}"],
["key-order-ascii", "{\"b\": 1, \"a\": 2, \"B\": 3, \"10\": 4, \"9\": 5}", "{\n \"10\": 4,\n \"9\": 5,\n \"B\": 3,\n \"a\": 2,\n \"b\": 1\n}"],
["key-order-prefix", "{\"ab\": 1, \"a\": 2, \"\": 3}", "{\n \"\": 3,\n \"a\": 2,\n \"ab\": 1\n}"],
["key-order-astral", "{\"😀\": 1, \"fi\": 2, \"é\": 3}", "{\n \"é\": 3,\n \"fi\": 2,\n \"😀\": 1\n}"],
["key-order-nested", "{\"z\": {\"y\": 1, \"x\": 2}, \"a\": [{\"d\": 1, \"c\": 2}]}", "{\n \"a\": [\n {\n \"c\": 2,\n \"d\": 1\n }\n ],\n \"z\": {\n \"x\": 2,\n \"y\": 1\n }\n}"],
["duplicate-name", "{\"a\": 1, \"b\": 0, \"a\": {\"c\": 3}}", "{\n \"a\": {\n \"c\": 3\n },\n \"b\": 0\n}"],
["big-int", "{\"id\": 9007199254740993}", "{\n \"id\": 9007199254740993\n}"],
["beyond-int64", "[18446744073709551617, -18446744073709551617]", "[\n 18446744073709551617,\n -18446744073709551617\n]"],
["negative-zero", "[-0, 0]", "[\n 0,\n 0\n]"],
["non-ascii", "[\"Zürich\", \"日本語\", \"😀\"]", "[\n \"Zürich\",\n \"日本語\",\n \"😀\"\n]"],
["escaped-non-ascii", "[\"\\u00e9\\ud83d\\ude00\"]", "[\n \"é😀\"\n]"],
["escapes", "[\"q\\\" b\\\\ s\\/ t\\t n\\n r\\r\"]", "[\n \"q\\\" b\\\\ s/ t\\t n\\n r\\r\"\n]"],
["control-chars", "[\"\\u0000\\u001f\\b\\f\\u007f\"]", "[\n \"\\u0000\\u001f\\b\\f\u007f\"\n]"],
["html-chars", "{\"html\": \"<a href='x'>&</a>\"}", "{\n \"html\": \"<a href='x'>&</a>\"\n}"],
["empty-containers", "{\"a\": {}, \"b\": [], \"c\": \"\"}", "{\n \"a\": {},\n \"b\": [],\n \"c\": \"\"\n}"],
["empty-object-root", "{}", "{}"],
["empty-array-root", "[ ]", "[]"],
["scalar-root", "42", "42"],
["string-root", "\"text\"", "\"text\""],
["literals", "[true, false, null]", "[\n true,\n false,\n null\n]"],
["whitespace-inside", "\n{ \"a\" :\t[ 1 , 2 ] }\r\n", "{\n \"a\": [\n 1,\n 2\n ]\n}"],
["already-pretty", "{\n \"a\": [\n 1,\n 2\n ],\n \"b\": {}\n}", "{\n \"a\": [\n 1,\n 2\n ],\n \"b\": {}\n}"],
["deep", "[[[[1]]]]", "[\n [\n [\n [\n 1\n ]\n ]\n ]\n]"],
];
// [case, text]; 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"],
["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"],
];
for (const [name, text, want] of cases) {
test(name, () => {
assert.equal(prettyJson(text), want);
// Pretty-printing the output again gives the same text.
assert.equal(prettyJson(want), want);
});
}
for (const [name, text] of invalid) {
test(name, () => {
assert.throws(() => prettyJson(text), SyntaxError);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pretty-print-json/.
// 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);
}
// JSON.stringify(value, null, 2) cannot write a BigInt, and it keeps the
// key order of the object, where integer-like keys such as "10" come first.
// So this function writes the arrays and objects, and JSON.stringify writes the strings.
function write(value: unknown, indent: string): string {
const inner = indent + " ";
if (typeof value === "bigint") return value.toString();
if (Array.isArray(value)) {
if (value.length === 0) return "[]";
const items = value.map((item) => inner + write(item, inner));
return `[\n${items.join(",\n")}\n${indent}]`;
}
if (isObject(value)) {
const keys = Object.keys(value).sort(byCodePoint);
if (keys.length === 0) return "{}";
const members = keys.map((key) => `${inner}${JSON.stringify(key)}: ${write(value[key], inner)}`);
return `{\n${members.join(",\n")}\n${indent}}`;
}
return JSON.stringify(value);
}
// Returns the JSON text indented by two spaces, with the names of each object sorted.
// Throws a SyntaxError when the text is not JSON.
export function prettyJson(text: string): string {
return write(JSON.parse(text, exactIntegers), "");
}
prettyJson.test.ts 73 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pretty-print-json/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { prettyJson } from "./prettyJson.ts";
// [case, text, the pretty text]
const cases: [string, string, string][] = [
["object", "{\"name\": \"Ada\", \"born\": 1815, \"tags\": [\"math\", \"code\"]}", "{\n \"born\": 1815,\n \"name\": \"Ada\",\n \"tags\": [\n \"math\",\n \"code\"\n ]\n}"],
["nested", "{\"user\": {\"id\": 7, \"roles\": [\"admin\"]}, \"ok\": true}", "{\n \"ok\": true,\n \"user\": {\n \"id\": 7,\n \"roles\": [\n \"admin\"\n ]\n }\n}"],
["array-of-objects", "[{\"a\": 1}, {\"b\": null}]", "[\n {\n \"a\": 1\n },\n {\n \"b\": null\n }\n]"],
["compact-input", "{\"a\":[1,2,{\"b\":false}]}", "{\n \"a\": [\n 1,\n 2,\n {\n \"b\": false\n }\n ]\n}"],
["key-order-ascii", "{\"b\": 1, \"a\": 2, \"B\": 3, \"10\": 4, \"9\": 5}", "{\n \"10\": 4,\n \"9\": 5,\n \"B\": 3,\n \"a\": 2,\n \"b\": 1\n}"],
["key-order-prefix", "{\"ab\": 1, \"a\": 2, \"\": 3}", "{\n \"\": 3,\n \"a\": 2,\n \"ab\": 1\n}"],
["key-order-astral", "{\"😀\": 1, \"fi\": 2, \"é\": 3}", "{\n \"é\": 3,\n \"fi\": 2,\n \"😀\": 1\n}"],
["key-order-nested", "{\"z\": {\"y\": 1, \"x\": 2}, \"a\": [{\"d\": 1, \"c\": 2}]}", "{\n \"a\": [\n {\n \"c\": 2,\n \"d\": 1\n }\n ],\n \"z\": {\n \"x\": 2,\n \"y\": 1\n }\n}"],
["duplicate-name", "{\"a\": 1, \"b\": 0, \"a\": {\"c\": 3}}", "{\n \"a\": {\n \"c\": 3\n },\n \"b\": 0\n}"],
["big-int", "{\"id\": 9007199254740993}", "{\n \"id\": 9007199254740993\n}"],
["beyond-int64", "[18446744073709551617, -18446744073709551617]", "[\n 18446744073709551617,\n -18446744073709551617\n]"],
["negative-zero", "[-0, 0]", "[\n 0,\n 0\n]"],
["non-ascii", "[\"Zürich\", \"日本語\", \"😀\"]", "[\n \"Zürich\",\n \"日本語\",\n \"😀\"\n]"],
["escaped-non-ascii", "[\"\\u00e9\\ud83d\\ude00\"]", "[\n \"é😀\"\n]"],
["escapes", "[\"q\\\" b\\\\ s\\/ t\\t n\\n r\\r\"]", "[\n \"q\\\" b\\\\ s/ t\\t n\\n r\\r\"\n]"],
["control-chars", "[\"\\u0000\\u001f\\b\\f\\u007f\"]", "[\n \"\\u0000\\u001f\\b\\f\u007f\"\n]"],
["html-chars", "{\"html\": \"<a href='x'>&</a>\"}", "{\n \"html\": \"<a href='x'>&</a>\"\n}"],
["empty-containers", "{\"a\": {}, \"b\": [], \"c\": \"\"}", "{\n \"a\": {},\n \"b\": [],\n \"c\": \"\"\n}"],
["empty-object-root", "{}", "{}"],
["empty-array-root", "[ ]", "[]"],
["scalar-root", "42", "42"],
["string-root", "\"text\"", "\"text\""],
["literals", "[true, false, null]", "[\n true,\n false,\n null\n]"],
["whitespace-inside", "\n{ \"a\" :\t[ 1 , 2 ] }\r\n", "{\n \"a\": [\n 1,\n 2\n ]\n}"],
["already-pretty", "{\n \"a\": [\n 1,\n 2\n ],\n \"b\": {}\n}", "{\n \"a\": [\n 1,\n 2\n ],\n \"b\": {}\n}"],
["deep", "[[[[1]]]]", "[\n [\n [\n [\n 1\n ]\n ]\n ]\n]"],
];
// [case, text]; the text is not JSON
const invalid: [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"],
["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"],
];
for (const [name, text, want] of cases) {
test(name, () => {
assert.equal(prettyJson(text), want);
// Pretty-printing the output again gives the same text.
assert.equal(prettyJson(want), want);
});
}
for (const [name, text] of invalid) {
test(name, () => {
assert.throws(() => prettyJson(text), SyntaxError);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pretty-print-json/.
// Package prettyjson writes a JSON text indented, with the names of each object sorted.
package prettyjson
import (
"bytes"
"encoding/json"
"errors"
"io"
"strings"
)
// PrettyJSON returns the JSON text indented by two spaces, with the names of each object sorted.
func PrettyJSON(text 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")
}
var out bytes.Buffer
enc := json.NewEncoder(&out)
// Without this, the encoder writes <, > and & as \u003c, \u003e and \u0026.
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
// 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
}
pretty_json_test.go 84 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pretty-print-json/.
package prettyjson
import "testing"
func TestCases(t *testing.T) {
cases := []struct {
name, text, want string
}{
{"object", "{\"name\": \"Ada\", \"born\": 1815, \"tags\": [\"math\", \"code\"]}", "{\n \"born\": 1815,\n \"name\": \"Ada\",\n \"tags\": [\n \"math\",\n \"code\"\n ]\n}"},
{"nested", "{\"user\": {\"id\": 7, \"roles\": [\"admin\"]}, \"ok\": true}", "{\n \"ok\": true,\n \"user\": {\n \"id\": 7,\n \"roles\": [\n \"admin\"\n ]\n }\n}"},
{"array-of-objects", "[{\"a\": 1}, {\"b\": null}]", "[\n {\n \"a\": 1\n },\n {\n \"b\": null\n }\n]"},
{"compact-input", "{\"a\":[1,2,{\"b\":false}]}", "{\n \"a\": [\n 1,\n 2,\n {\n \"b\": false\n }\n ]\n}"},
{"key-order-ascii", "{\"b\": 1, \"a\": 2, \"B\": 3, \"10\": 4, \"9\": 5}", "{\n \"10\": 4,\n \"9\": 5,\n \"B\": 3,\n \"a\": 2,\n \"b\": 1\n}"},
{"key-order-prefix", "{\"ab\": 1, \"a\": 2, \"\": 3}", "{\n \"\": 3,\n \"a\": 2,\n \"ab\": 1\n}"},
{"key-order-astral", "{\"😀\": 1, \"fi\": 2, \"é\": 3}", "{\n \"é\": 3,\n \"fi\": 2,\n \"😀\": 1\n}"},
{"key-order-nested", "{\"z\": {\"y\": 1, \"x\": 2}, \"a\": [{\"d\": 1, \"c\": 2}]}", "{\n \"a\": [\n {\n \"c\": 2,\n \"d\": 1\n }\n ],\n \"z\": {\n \"x\": 2,\n \"y\": 1\n }\n}"},
{"duplicate-name", "{\"a\": 1, \"b\": 0, \"a\": {\"c\": 3}}", "{\n \"a\": {\n \"c\": 3\n },\n \"b\": 0\n}"},
{"big-int", "{\"id\": 9007199254740993}", "{\n \"id\": 9007199254740993\n}"},
{"beyond-int64", "[18446744073709551617, -18446744073709551617]", "[\n 18446744073709551617,\n -18446744073709551617\n]"},
{"negative-zero", "[-0, 0]", "[\n 0,\n 0\n]"},
{"non-ascii", "[\"Zürich\", \"日本語\", \"😀\"]", "[\n \"Zürich\",\n \"日本語\",\n \"😀\"\n]"},
{"escaped-non-ascii", "[\"\\u00e9\\ud83d\\ude00\"]", "[\n \"é😀\"\n]"},
{"escapes", "[\"q\\\" b\\\\ s\\/ t\\t n\\n r\\r\"]", "[\n \"q\\\" b\\\\ s/ t\\t n\\n r\\r\"\n]"},
{"control-chars", "[\"\\u0000\\u001f\\b\\f\\u007f\"]", "[\n \"\\u0000\\u001f\\b\\f\u007f\"\n]"},
{"html-chars", "{\"html\": \"<a href='x'>&</a>\"}", "{\n \"html\": \"<a href='x'>&</a>\"\n}"},
{"empty-containers", "{\"a\": {}, \"b\": [], \"c\": \"\"}", "{\n \"a\": {},\n \"b\": [],\n \"c\": \"\"\n}"},
{"empty-object-root", "{}", "{}"},
{"empty-array-root", "[ ]", "[]"},
{"scalar-root", "42", "42"},
{"string-root", "\"text\"", "\"text\""},
{"literals", "[true, false, null]", "[\n true,\n false,\n null\n]"},
{"whitespace-inside", "\n{ \"a\" :\t[ 1 , 2 ] }\r\n", "{\n \"a\": [\n 1,\n 2\n ]\n}"},
{"already-pretty", "{\n \"a\": [\n 1,\n 2\n ],\n \"b\": {}\n}", "{\n \"a\": [\n 1,\n 2\n ],\n \"b\": {}\n}"},
{"deep", "[[[[1]]]]", "[\n [\n [\n [\n 1\n ]\n ]\n ]\n]"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got, err := PrettyJSON(c.text)
if err != nil {
t.Fatal(err)
}
if got != c.want {
t.Errorf("got %q, want %q", got, c.want)
}
// Pretty-printing the output again gives the same text.
if again, _ := PrettyJSON(got); again != got {
t.Errorf("not idempotent: %q", again)
}
})
}
}
func TestInvalidJSON(t *testing.T) {
cases := []struct{ name, text 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"},
{"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"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got, err := PrettyJSON(c.text); err == nil {
t.Errorf("got %q and no error", got)
}
})
}
}
References
- T. Bray (Ed.), RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format, December 2017, 2 JSON Grammar; 4 Objects
- jq Manual, Invoking jq (--indent, --sort-keys); Basic filters, Identity
- The Python Standard Library, json, JSON encoder and decoder, json.dump (indent, sort_keys, ensure_ascii); Command-line interface
- MDN Web Docs, JSON.stringify(), Parameters (space)
- MDN Web Docs, JSON.parse(), Parameters (reviver, context.source)
- .NET documentation, How to write .NET objects as JSON (serialize), Serialize to formatted JSON
- .NET documentation, How to customize character encoding with System.Text.Json, the introduction
- Go standard library, package encoding/json, func Marshal; func MarshalIndent; Encoder.SetIndent; Encoder.SetEscapeHTML
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 1TN7KC Edit this page History Report an error Markdown