Programming Search⌘K

Formatcore

JSON

Also called JavaScript Object Notation.

JSON is a text format for structured data, based on the object and array literals of JavaScript. A value is an object, an array, a string, a number, true, false or null.

What it is

JSON (JavaScript Object Notation) is a text format for structured data. A JSON text is one value. A value is an object, an array, a number, a string, or one of the three literal names true, false and null.1 An object is a set of name and value pairs, and an array is an ordered list of values. These two structures map to the record, the dictionary and the list of most programming languages. For this reason, JSON is the usual format of web APIs, configuration files and log records.

Two documents define the format. RFC 8259 of the IETF defines the grammar and adds rules for interoperability, such as the character encoding.1 ECMA-404 defines the same grammar and nothing more.2 The grammar is very small. It has no comments, no dates, no binary data, no references and no schema. Each of these gaps causes a family of pitfalls, and other documents fill some of them (see Versions and Tools and libraries).

JSON describes syntax, not a data model. The text 1.0 and the text 1 are two different texts, and the grammar does not say if they are the same number. The text {"a": 1, "a": 2} matches the grammar, and the grammar does not say which value wins. Each parser makes its own choice, and the choices differ between languages. The examples of this page show these differences.

History

Douglas Crockford and Chip Morningstar sent the first JSON message in 2001, at their company State Software. They used it for the communication between the browser and the server, and between the servers of their platform.6 The format was a subset of the JavaScript object literal, so a browser could read it with the JavaScript compiler. The first message failed because it had the name do, a reserved word. In the third edition of ECMAScript, a reserved word must have quotes when it is a name in an object literal. Crockford did not want to put the list of reserved words in the grammar, so he made quotes necessary for all names.6 The first grammar had comments. Crockford removed them because people used them to give instructions to the parser, and this broke interoperability.6

Crockford bought the domain json.org late in 2002 and put the grammar on one page.6 The page says that JSON is based on a subset of the third edition of ECMA-262.5 Crockford says that he discovered JSON and did not invent it, because the notation was already in JavaScript.6 RFC 4627 registered the media type application/json in July 2006.7 RFC 7159 replaced it in March 2014.8 RFC 8259 and the second edition of ECMA-404 came out together in December 2017, with the same grammar.12

Syntax or structure

RFC 8259 gives the grammar in ABNF. The rules below are copied from Sections 2 to 7.1

JSON-text = ws value ws

value = false / null / true / object / array / number / string

object = begin-object [ member *( value-separator member ) ] end-object
member = string name-separator value
array = begin-array [ value *( value-separator value ) ] end-array

number = [ minus ] int [ frac ] [ exp ]
int = zero / ( digit1-9 *DIGIT )
frac = decimal-point 1*DIGIT
exp = e [ minus / plus ] 1*DIGIT

string = quotation-mark *char quotation-mark
char = unescaped /
    escape (
        %x22 /          ; "    quotation mark  U+0022
        %x5C /          ; \    reverse solidus U+005C
        %x2F /          ; /    solidus         U+002F
        %x62 /          ; b    backspace       U+0008
        %x66 /          ; f    form feed       U+000C
        %x6E /          ; n    line feed       U+000A
        %x72 /          ; r    carriage return U+000D
        %x74 /          ; t    tab             U+0009
        %x75 4HEXDIG )  ; uXXXX                U+XXXX
unescaped = %x20-21 / %x23-5B / %x5D-10FFFF

ws = *( %x20 / %x09 / %x0A / %x0D )

The structural characters are [, ], {, }, : and ,. Whitespace is allowed around each of them. Only four characters are whitespace: space, tab, line feed and carriage return.1

The top level can be any value, not only an object or an array. RFC 4627 allowed only an object or an array at the top level, and RFC 7159 removed this limit.8

Names are strings. RFC 8259 says that the names in an object SHOULD be unique. When they are not unique, "the behavior of software that receives such an object is unpredictable".1 The order of the members is not part of the meaning of an object, but the order of the values in an array is.

A number is a decimal with an optional sign, fraction and exponent. The grammar has no leading zeros, no leading plus sign, no hexadecimal, no NaN and no Infinity. The grammar puts no limit on the size or the precision of a number. RFC 8259 lets an implementation set limits. It says that IEEE 754 binary64 (the double type) is widely used. So only integers in the range from -(2^53)+1 to (2^53)-1 are certain to keep their exact value between implementations.1

A string is a sequence of Unicode characters in double quotes. The quotation mark, the reverse solidus and the control characters U+0000 to U+001F must be escaped. Any other character can be in the string as it is, or as a \uXXXX escape. A character outside the Basic Multilingual Plane is written as two escapes, a UTF-16 surrogate pair. The grammar also accepts a single escape of a surrogate, such as "\uDEAD". This is not a valid Unicode string, and RFC 8259 says that the behaviour of software on it is unpredictable.1

JSON text that goes between systems that are not part of a closed ecosystem MUST be encoded in UTF-8. A generator MUST NOT add a byte order mark, and a parser MAY ignore one.1 A parser MUST accept every text that matches the grammar. It MAY accept extensions, and it MAY set limits on the size of a text, the depth of nesting, the range of numbers and the length of strings.1

Examples

The text below is one JSON value. It shows each type of the grammar.

{
  "id": 9007199254740993,
  "total": 0.10,
  "tags": ["new", "paid"],
  "customer": {"name": "Hà Nội Café", "vip": true},
  "note": null
}

The integer 9007199254740993 is 2^53 + 1. It is a valid JSON number, but a double cannot hold it. A parser that reads every number as a double gets 2^53. Python reads an integer without a fraction as an int, so it keeps the value. The option parse_int=float shows what a double-based parser does.16

import json

text = '{"id": 9007199254740993}'
print(json.loads(text)["id"])
print(json.loads(text, parse_int=float)["id"])
print(float(2**53) == float(2**53 + 1))
Output
9007199254740993
9007199254740992.0
True

A JSON string is a sequence of characters, but escapes use UTF-16 code units. The musical symbol G clef, U+1D11E, is one character and takes two escapes. A lone surrogate escape parses, but the result cannot be encoded as UTF-8.

import json

clef = json.loads('"\\ud834\\udd1e"')
print(clef, len(clef), len(clef.encode("utf-8")))

lone = json.loads('"\\udead"')
print(len(lone))
try:
    lone.encode("utf-8")
except UnicodeEncodeError as error:
    print(error.reason)
Output
𝄞 1 4
1
surrogates not allowed

Two texts can hold the same data and differ as bytes. To compare or sign JSON data, a program must write it in one fixed form. The function canonical below sorts the names and removes the whitespace. This is close to the scheme of RFC 8785, but it is not the same (see Versions).

import json

first = {"b": [1, 2], "a": "x"}
second = json.loads('{ "a" : "x", "b" : [ 1, 2 ] }')
print(json.dumps(first) == json.dumps(second))


def canonical(value):
    return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False)


print(canonical(first))
print(canonical(first) == canonical(second))
Output
False
{"a":"x","b":[1,2]}
True

The example files show the parse and serialise functions of each language, and the differences on numbers, repeated names, invalid strings and NaN.

PythonGitHub
import json
from decimal import Decimal

text = '{"id": 9007199254740993, "total": 0.10, "tags": ["new"], "paid": false, "note": null}'

order = json.loads(text)
print(order)
print(json.dumps(order, separators=(",", ":"), sort_keys=True))
print(json.dumps({"city": "Hà Nội"}))
print(json.dumps({"city": "Hà Nội"}, ensure_ascii=False))

exact = json.loads(text, parse_float=Decimal)
print(repr(exact["total"]))
Output
{'id': 9007199254740993, 'total': 0.1, 'tags': ['new'], 'paid': False, 'note': None}
{"id":9007199254740993,"note":null,"paid":false,"tags":["new"],"total":0.1}
{"city": "H\u00e0 N\u1ed9i"}
{"city": "Hà Nội"}
Decimal('0.10')
import json
from datetime import date

before = {1: "one", "pair": (1, 2), "ratio": float("nan")}
after = json.loads(json.dumps(before))
print(after)

try:
    json.dumps({"day": date(2026, 11, 10)})
except TypeError as error:
    print("TypeError:", error)

print(json.loads('{"total": 1, "total": 2}'))
Output
{'1': 'one', 'pair': [1, 2], 'ratio': nan}
TypeError: Object of type date is not JSON serializable
{'total': 2}
import json


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


def reject_constant(name):
    raise ValueError(f"{name} is not JSON")


for text in ['{"total": 1, "total": 2}', "[NaN]"]:
    try:
        json.loads(text, object_pairs_hook=reject_duplicates, parse_constant=reject_constant)
    except ValueError as error:
        print(error)

try:
    json.dumps(float("inf"), allow_nan=False)
except ValueError as error:
    print(error)
Output
duplicate names in ['total', 'total']
NaN is not JSON
Out of range float values are not JSON compliant: inf
  • Verdict: stdlib. The json module parses with json.loads (a string) and json.load (a file), and writes with json.dumps and json.dump.
  • A JSON integer becomes an int of any size, so 9007199254740993 survives. A JSON number with a fraction or an exponent becomes a float. parse_float=Decimal keeps the exact decimal text.
  • By default dumps escapes every non-ASCII character as \uXXXX. ensure_ascii=False writes the characters as they are.
  • The defaults accept and write NaN, Infinity and -Infinity, which are not JSON. allow_nan=False and parse_constant turn them into errors.
  • A repeated name keeps the last value. object_pairs_hook sees every pair and can reject the object.
  • An integer key becomes a string, a tuple becomes a list, and a date needs a default function or a conversion to an ISO 8601 string first.
  • An integer with more than 4300 digits raises ValueError, because CPython limits the length of integer strings to protect against slow conversions.
#include <nlohmann/json.hpp>
#include <print>
#include <string>
#include <vector>

struct Order {
    std::uint64_t id;
    double total;
    std::vector<std::string> tags;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Order, id, total, tags)

int main() {
    auto text = R"({"id": 9007199254740993, "total": 0.10, "tags": ["new"]})";

    nlohmann::json tree = nlohmann::json::parse(text);
    auto order = tree.get<Order>();
    std::println("{} {} {}", order.id, order.total, order.tags.at(0));

    nlohmann::json back = order;
    std::println("{}", back.dump());
    std::println("{}", back.dump(2));
}
Output
9007199254740993 0.1 new
{"id":9007199254740993,"tags":["new"],"total":0.1}
{
  "id": 9007199254740993,
  "tags": [
    "new"
  ],
  "total": 0.1
}
#include <cmath>
#include <nlohmann/json.hpp>
#include <print>
#include <string>

int main() {
    using nlohmann::json;

    std::println("{}", json::parse(R"({"total": 1, "total": 2})").dump());
    std::println("{}", json::parse("18446744073709551616").dump());
    std::println("{}", json(NAN).dump());

    auto ordered = nlohmann::ordered_json::parse(R"({"zeta": 1, "alpha": 2})");
    std::println("{}", ordered.dump());

    try {
        json bad = std::string("\xff");
        std::println("{}", bad.dump());
    } catch (const json::type_error& error) {
        std::println("{}", error.what());
    }

    try {
        auto bad = json::parse(R"({"total": 1,})");
        std::println("{}", bad.dump());
    } catch (const json::parse_error& error) {
        std::println("{}", error.what());
    }
}
Output
{"total":2}
1.8446744073709552e+19
null
{"zeta":1,"alpha":2}
[json.exception.type_error.316] invalid UTF-8 byte at index 0: 0xFF
[json.exception.parse_error.101] parse error at line 1, column 13: syntax error while parsing object key - unexpected '}'; expected string literal
  • Verdict: library. The C++ standard library has no JSON. The examples use nlohmann/json 3.12.0, a header-only library. Boost.JSON, RapidJSON and simdjson are other common choices.
  • json::parse reads text into a json value, and dump() writes it, compact or with an indent. get<T>() and assignment convert to and from a type that has to_json and from_json, here made by NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE.
  • The json type stores objects in a std::map, so dump() writes the names in sorted order. nlohmann::ordered_json keeps the input order.
  • An integer keeps 64 bits, as std::int64_t or std::uint64_t. A larger integer becomes a double.
  • A repeated name keeps the last value. NaN writes as null.
  • dump() throws type_error.316 for a string that is not valid UTF-8. A syntax error throws parse_error.101 with the line and the column.
JavaGitHub
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.ToNumberPolicy;
import com.google.gson.reflect.TypeToken;
import java.util.List;
import java.util.Map;

public class Main {
    record Order(long id, double total, List<String> tags, boolean paid) {}

    public static void main(String[] args) {
        String text = "{\"id\": 9007199254740993, \"total\": 0.10, \"tags\": [\"new\"], \"paid\": false}";
        Gson gson = new Gson();

        Order order = gson.fromJson(text, Order.class);
        System.out.println(order);
        System.out.println(gson.toJson(order));

        Map<String, Object> loose = gson.fromJson(text, new TypeToken<Map<String, Object>>() {}.getType());
        System.out.println(loose.get("id"));

        Gson exact = new GsonBuilder().setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE).create();
        Map<String, Object> kept = exact.fromJson(text, new TypeToken<Map<String, Object>>() {}.getType());
        System.out.println(kept.get("id"));
    }
}
Output
Order[id=9007199254740993, total=0.1, tags=[new], paid=false]
{"id":9007199254740993,"total":0.1,"tags":["new"],"paid":false}
9.007199254740992E15
9007199254740993
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import java.util.Map;

public class Main {
    static class Invoice {
        long total;
        String currency;
    }

    public static void main(String[] args) {
        Gson gson = new Gson();
        String repeated = "{\"total\": 1, \"total\": 2}";

        try {
            gson.fromJson(repeated, new TypeToken<Map<String, Object>>() {}.getType());
        } catch (JsonSyntaxException error) {
            System.out.println(error.getMessage());
        }
        System.out.println(JsonParser.parseString(repeated));

        Invoice empty = gson.fromJson("{}", Invoice.class);
        System.out.println(empty.total + " " + empty.currency);

        System.out.println(gson.toJson("<a href='x'>"));
        System.out.println(new GsonBuilder().disableHtmlEscaping().create().toJson("<a href='x'>"));

        try {
            gson.toJson(Double.NaN);
        } catch (IllegalArgumentException error) {
            System.out.println(error.getClass().getSimpleName());
        }
    }
}
Output
duplicate key: total
{"total":2}
0 null
"\u003ca href\u003d\u0027x\u0027\u003e"
"<a href='x'>"
IllegalArgumentException
  • Verdict: library. Java SE has no JSON API. The examples use Gson 2.10.1. Jackson (ObjectMapper) is the other common library, and Jakarta JSON Processing is the API of Jakarta EE.
  • Gson.fromJson maps text to a class or a record, and Gson.toJson writes it. JsonParser.parseString gives a tree of JsonElement values.
  • A long field keeps the integer exactly. In a Map<String, Object>, Gson makes every number a Double by default, so 9007199254740993 loses its last digit. ToNumberPolicy.LONG_OR_DOUBLE keeps integers as Long.
  • A repeated name makes the map adapter throw duplicate key. The tree parser keeps the last value.
  • A missing member leaves the field at its default, 0 or null. Gson does not report it.
  • By default Gson escapes <, >, =, & and ' so the output is safe inside HTML. disableHtmlEscaping() turns this off.
  • NaN and the infinities throw, unless the builder calls serializeSpecialFloatingPointValues().
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;

const string text = """{"id": 9007199254740993, "total": 0.10, "tags": ["new"], "paid": false}""";

Order order = JsonSerializer.Deserialize(text, AppJson.Default.Order)!;
Console.WriteLine($"{order.Id} {order.Total} {string.Join(",", order.Tags)} {order.Paid}");
Console.WriteLine(JsonSerializer.Serialize(order, AppJson.Default.Order));

JsonNode tree = JsonNode.Parse(text)!;
Console.WriteLine(tree["id"]!.GetValue<long>());
Console.WriteLine(tree["id"]!.GetValue<double>());

[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(Order))]
partial class AppJson : JsonSerializerContext;

record Order(long Id, decimal Total, string[] Tags, bool Paid);
Output
9007199254740993 0.10 new False
{"id":9007199254740993,"total":0.10,"tags":["new"],"paid":false}
9007199254740993
9007199254740992
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;

const string repeated = """{"total": 1, "total": 2}""";
Console.WriteLine(JsonNode.Parse(repeated)!.ToJsonString());
Console.WriteLine(JsonSerializer.Deserialize(repeated, AppJson.Default.Invoice)!.Total);

try
{
    JsonNode.Parse(repeated, documentOptions: new JsonDocumentOptions { AllowDuplicateProperties = false });
}
catch (JsonException error)
{
    Console.WriteLine(error.Message);
}

Console.WriteLine(JsonSerializer.Serialize("Hà Nội <b>", AppJson.Default.String));

try
{
    JsonSerializer.Serialize(double.NaN, AppJson.Default.Double);
}
catch (ArgumentException error)
{
    Console.WriteLine(error.GetType().Name);
}

[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(Invoice))]
[JsonSerializable(typeof(string))]
[JsonSerializable(typeof(double))]
partial class AppJson : JsonSerializerContext;

record Invoice(int Total);
Output
{"total":1,"total":2}
2
Duplicate property 'total' encountered during deserialization.
"H\u00E0 N\u1ED9i \u003Cb\u003E"
ArgumentException
  • Verdict: stdlib. System.Text.Json is part of .NET. JsonSerializer maps JSON to types, JsonDocument gives a read-only tree, JsonNode gives a tree that can change, and Utf8JsonReader and Utf8JsonWriter read and write tokens.
  • The examples use a source-generated JsonSerializerContext. A file-based app is compiled for native AOT by default, and that turns off the reflection-based serializer.
  • A long field keeps the integer exactly, and a decimal keeps 0.10 with its scale. GetValue<double>() rounds to the nearest double.
  • JsonNode.Parse keeps both members of a repeated name, and the serializer keeps the last value. AllowDuplicateProperties = false makes both reject the text.
  • The default encoder escapes non-ASCII characters and the HTML characters <, >, & and '. JavaScriptEncoder.UnsafeRelaxedJsonEscaping or an encoder with a wider UnicodeRange writes more characters as they are.
  • NaN and the infinities throw, unless JsonNumberHandling.AllowNamedFloatingPointLiterals is set.
JavaScriptGitHub
const text = '{"id": 9007199254740993, "total": 0.10, "tags": ["new"], "paid": false, "note": null}';

const order = JSON.parse(text);
console.log(order.id);
console.log(JSON.stringify(order));
console.log(JSON.stringify({ city: "Hà Nội" }, null, 2));

const exact = JSON.parse(text, (key, value, context) =>
  key === "id" ? BigInt(context.source) : value,
);
console.log(exact.id);
console.log(JSON.stringify({ id: JSON.rawJSON(exact.id.toString()) }));
Output
9007199254740992
{"id":9007199254740992,"total":0.1,"tags":["new"],"paid":false,"note":null}
{
  "city": "Hà Nội"
}
9007199254740993n
{"id":9007199254740993}
const before = {
  ratio: NaN,
  limit: Infinity,
  missing: undefined,
  day: new Date(Date.UTC(2026, 10, 10)),
  counts: new Map([["a", 1]]),
};
const text = JSON.stringify(before);
console.log(text);
console.log(typeof JSON.parse(text).day);

try {
  JSON.stringify({ id: 1n });
} catch (error) {
  console.log(`${error.name}: ${error.message}`);
}

console.log(JSON.parse('{"total": 1, "total": 2}'));
Output
{"ratio":null,"limit":null,"day":"2026-11-10T00:00:00.000Z","counts":{}}
string
TypeError: Do not know how to serialize a BigInt
{ total: 2 }
  • Verdict: native. JSON is a built-in object of the language. JSON.parse reads text and JSON.stringify writes it.
  • Every JSON number becomes a Number, an IEEE 754 double. 9007199254740993 is above 2^53, so it reads as 9007199254740992 with no error.
  • The reviver of JSON.parse gets a third argument with the source text of each primitive value, and JSON.rawJSON writes a number from its text. With both, a large integer can travel as a BigInt.
  • NaN and Infinity become null. A property whose value is undefined or a function is left out. A Date becomes its ISO string through toJSON, and it comes back as a string. A Map becomes {}.
  • A BigInt value makes JSON.stringify throw a TypeError, unless a replacer or a toJSON method converts it.
  • A repeated name keeps the last value.
TypeScriptGitHub
interface Order {
  id: number;
  total: number;
  tags: string[];
}

function isOrder(value: unknown): value is Order {
  if (typeof value !== "object" || value === null) {
    return false;
  }
  const record = value as Record<string, unknown>;
  return (
    typeof record.id === "number" &&
    typeof record.total === "number" &&
    Array.isArray(record.tags) &&
    record.tags.every((tag) => typeof tag === "string")
  );
}

for (const text of ['{"id": 7, "total": 0.1, "tags": ["new"]}', '{"id": "7", "total": 0.1}']) {
  const data: unknown = JSON.parse(text);
  if (isOrder(data)) {
    console.log("order", data.id, JSON.stringify(data));
  } else {
    console.log("rejected", text);
  }
}
Output
order 7 {"id":7,"total":0.1,"tags":["new"]}
rejected {"id": "7", "total": 0.1}
interface Meeting {
  title: string;
  at: Date;
}

const meeting: Meeting = { title: "review", at: new Date(Date.UTC(2026, 10, 10)) };
const copy = JSON.parse(JSON.stringify(meeting)) as Meeting;
console.log(typeof copy.at);
console.log(copy.at instanceof Date);

const nothing: string = JSON.stringify(undefined);
console.log(nothing === undefined);
Output
string
false
true
  • Verdict: native. TypeScript uses the JSON object of JavaScript, with the same rules for numbers, NaN, undefined and repeated names.
  • JSON.parse returns any. A type assertion such as as Meeting checks nothing at run time. In the second example the type says Date, but the value is a string.
  • Assign the result to unknown and check it with a type guard, or with a schema validator, before the code uses it as a typed value.
  • The declared return type of JSON.stringify is string, but the call returns undefined for undefined, a function or a symbol.
package main

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

type Order struct {
	ID    int64    `json:"id"`
	Total float64  `json:"total"`
	Tags  []string `json:"tags"`
	Note  *string  `json:"note,omitempty"`
}

func main() {
	text := `{"id": 9007199254740993, "total": 0.10, "tags": ["new"], "note": null}`

	var order Order
	if err := json.Unmarshal([]byte(text), &order); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("%+v\n", order)

	out, _ := json.Marshal(order)
	fmt.Println(string(out))

	var loose map[string]any
	json.Unmarshal([]byte(text), &loose)
	fmt.Println(loose["id"])

	decoder := json.NewDecoder(strings.NewReader(text))
	decoder.UseNumber()
	var exact map[string]any
	decoder.Decode(&exact)
	fmt.Println(exact["id"])
}
Output
{ID:9007199254740993 Total:0.1 Tags:[new] Note:<nil>}
{"id":9007199254740993,"total":0.1,"tags":["new"]}
9.007199254740992e+15
9007199254740993
package main

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

type Order struct {
	ID int64 `json:"id"`
}

func main() {
	var order Order
	err := json.Unmarshal([]byte(`{"ID": 1, "id": 2, "Id": 3, "extra": true}`), &order)
	fmt.Println(order.ID, err)

	strict := json.NewDecoder(strings.NewReader(`{"id": 1, "extra": true}`))
	strict.DisallowUnknownFields()
	fmt.Println(strict.Decode(&order))

	out, _ := json.Marshal(map[string]string{"html": "<b>&</b>"})
	fmt.Println(string(out))

	_, err = json.Marshal(math.NaN())
	fmt.Println(err)

	var text string
	json.Unmarshal([]byte("\"\xff\""), &text)
	fmt.Printf("%q\n", text)
}
Output
3 <nil>
json: unknown field "extra"
{"html":"\u003cb\u003e\u0026\u003c/b\u003e"}
json: unsupported value: NaN
"�"
  • Verdict: stdlib. The package encoding/json has Marshal and Unmarshal for byte slices, and Encoder and Decoder for streams. Struct tags name the JSON members.
  • A typed field keeps the integer exactly. A value decoded into any becomes a float64, so 9007199254740993 loses its last digit. Decoder.UseNumber keeps the text as a json.Number.
  • Unmarshal matches member names to fields without regard to case, and a later member overwrites an earlier one. In the second example "ID", "id" and "Id" all fill the field ID, and the last one wins.
  • Unknown members are ignored unless the decoder calls DisallowUnknownFields.
  • Marshal escapes <, > and & so the output is safe inside HTML. It returns an error for NaN and the infinities.
  • Invalid UTF-8 in a string becomes U+FFFD with no error.
  • The package encoding/json/v2 has stricter defaults: it matches names with case, and it rejects duplicate names and invalid UTF-8.
RustGitHub
use serde::{Deserialize, Serialize};
use serde_json::Value;

#[derive(Debug, Serialize, Deserialize)]
struct Order {
    id: u64,
    total: f64,
    tags: Vec<String>,
    note: Option<String>,
}

fn main() -> Result<(), serde_json::Error> {
    let text = r#"{"id": 9007199254740993, "total": 0.10, "tags": ["new"], "note": null}"#;

    let order: Order = serde_json::from_str(text)?;
    println!("{order:?}");
    println!("{}", serde_json::to_string(&order)?);

    let tree: Value = serde_json::from_str(text)?;
    println!("{}", tree["id"]);
    println!("{}", tree["tags"][0]);
    Ok(())
}
Output
Order { id: 9007199254740993, total: 0.1, tags: ["new"], note: None }
{"id":9007199254740993,"total":0.1,"tags":["new"],"note":null}
9007199254740993
"new"
use serde::Deserialize;
use serde_json::Value;

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct Invoice {
    total: u64,
}

fn main() {
    let repeated = r#"{"total": 1, "total": 2}"#;
    println!("{:?}", serde_json::from_str::<Invoice>(repeated));
    println!("{}", serde_json::from_str::<Value>(repeated).unwrap());

    let big: Value = serde_json::from_str("18446744073709551616").unwrap();
    println!("{big}");

    println!("{}", serde_json::to_string(&f64::NAN).unwrap());

    let tree: Value = serde_json::from_str(r#"{"zeta": 1, "alpha": 2}"#).unwrap();
    println!("{tree}");
}
Output
Err(Error("duplicate field `total`", line: 1, column: 20))
{"total":2}
1.8446744073709552e+19
null
{"alpha":2,"zeta":1}
  • Verdict: library. The Rust standard library has no JSON. The examples use serde_json 1.0.154 with serde 1.0.229 and the derive feature.
  • serde_json::from_str, from_slice and from_reader parse into a type that implements Deserialize. to_string, to_string_pretty and to_writer write a type that implements Serialize.
  • Value keeps an integer as u64 or i64 when it fits, so 9007199254740993 survives. An integer above u64::MAX becomes an f64, unless the crate is built with the feature arbitrary_precision.
  • A derived struct rejects a repeated field. A Value keeps the last one.
  • NaN and the infinities serialize as null.
  • Value keeps object members in a BTreeMap, sorted by name. The feature preserve_order keeps the order of the input.

Versions

The grammar has not changed in its substance since RFC 4627. The changes between the documents are about the top level, the encoding and the wording.

Document Date Status Change
json.org 2002 web page the first published grammar6
RFC 4627 July 2006 Informational registers application/json; the top level is an object or an array7
ECMA-404, 1st edition October 2013 Ecma standard the grammar only
RFC 7159 March 2014 Standards Track any value at the top level; obsoletes RFC 46278
RFC 8259 December 2017 Internet Standard (STD 90) UTF-8 is required for open exchange; obsoletes RFC 71591
ECMA-404, 2nd edition December 2017 Ecma standard the same grammar as RFC 8259; also ISO/IEC 21778:20172

JSON was a subset of JavaScript in its intent, but not in fact. A JSON string can hold the characters U+2028 (line separator) and U+2029 (paragraph separator) as they are, and a JavaScript string literal could not. The TC39 proposal "Subsume JSON" changed ECMAScript in 2019 to allow these two characters in string literals.10 The fifth edition of ECMA-262 added the built-in object JSON with parse and stringify, and the language specification still defines them.9

I-JSON

RFC 7493 defines I-JSON, a profile of JSON for messages on the Internet. An I-JSON text is also a JSON text, with more rules.3 It MUST be UTF-8, and its strings MUST NOT hold surrogates or noncharacters. Its numbers SHOULD stay within the range and the precision of binary64. A value that needs more range or more precision, such as a 64-bit identifier, is RECOMMENDED to be a string. The names in an object MUST be unique. The document also recommends an object or an array at the top level, the time format of RFC 3339 for dates, and base64url for binary data.3

Canonical JSON (RFC 8785)

The JSON Canonicalization Scheme (JCS) of RFC 8785 makes one fixed byte form for each JSON value, so a program can hash or sign it. The input must be I-JSON. The output has no whitespace. The names of each object are sorted, at each level, by their UTF-16 code units. Strings use the shortest escapes, and numbers use the algorithm Number::toString of ECMAScript. NaN, the infinities and lone surrogates are errors. The output is UTF-8.4

The function canonical in Examples differs from JCS on two points. Python sorts names by code point, not by UTF-16 code unit, so the order can differ for names with characters outside the Basic Multilingual Plane. Python also writes numbers in its own form: it writes 1e20 as 1e+20 and -0.0 as -0.0, and ECMAScript writes 100000000000000000000 and 0.

JSON5

JSON5 is a superset of JSON, based on the syntax of ECMAScript 5.1. Its version 1.0.0 is from March 2018.11 It adds comments, trailing commas, names without quotes, strings in single quotes, strings over more than one line, hexadecimal numbers, Infinity, NaN, a decimal point at the start or the end of a number, and a plus sign. JSON5 is for files that people write, such as configuration. A JSON parser does not accept JSON5.

JSON Lines and JSON text sequences

JSON Lines puts one JSON value on each line of a UTF-8 file, with no byte order mark. The line separator is \n, and a blank line is not valid. The extension is .jsonl.12 A program can append a record to the file and read the file one line at a time, without the parse of the whole file. A value in JSON Lines must not hold a raw line feed. A compact JSON writer never puts one there, because a line feed inside a string must be escaped.

RFC 7464 defines JSON text sequences, with the media type application/json-seq. Each JSON text starts with the ASCII record separator (0x1E) and ends with a line feed.13 The record separator lets a parser find the start of the next text after a broken one.

Pitfalls

  • Large integers. A parser that maps every number to a double changes integers above 2^53 with no error. JavaScript, the any path of Go, and the default Map path of Gson all do this. Send identifiers and money amounts as strings, or use a parser option that keeps the exact text.
  • Decimal fractions. 0.10 becomes the nearest double. Python with parse_float=decimal.Decimal, C# with decimal and Go with json.Number keep the decimal value.
  • Repeated names. Most parsers keep the last value with no warning. Some reject the text, and the .NET tree keeps both members. When two systems read the same text with different rules, they can see different data. Reject repeated names at a trust boundary, as I-JSON requires.3
  • NaN and the infinities. They are not JSON. Python writes NaN and Infinity by default, and its parser accepts them. JavaScript, serde_json and nlohmann/json write null. Go, Gson and System.Text.Json raise an error.
  • Dates, bytes and other types. JSON has no date and no binary type. Each library writes them in its own way, or refuses. Agree on a form, such as RFC 3339 strings for times and base64url for bytes.3
  • Types that do not round-trip. A JSON object name is always a string, so an integer key comes back as a string. A tuple or a set comes back as an array. A field that is missing in the text gets its default value in Go, Java and Rust structs, with no error.
  • Invalid Unicode. A lone surrogate escape passes the grammar. Go replaces invalid UTF-8 with U+FFFD, and nlohmann/json throws when it writes it. Validate strings at the boundary.
  • Deep nesting and large texts. A recursive parser can run out of stack on a text with very deep nesting. Set limits on depth and size for input from outside, as RFC 8259 allows.1
  • JSON inside HTML. The text </script> inside a JSON string ends a script element. Go, Gson and .NET escape <, > and & by default for this reason. Python and JavaScript do not.
  • eval. JSON was once read with the JavaScript eval function. This runs any code in the text. Use JSON.parse.
  • Comments in configuration files. JSON has no comments. A file that has them is not JSON, and a strict parser rejects it. JSON5 allows them.

Tools and libraries

Language Verdict Parse and serialise
Python stdlib json.loads, json.dumps16
JavaScript, TypeScript native JSON.parse, JSON.stringify9
Go stdlib json.Unmarshal, json.Marshal17
C# stdlib JsonSerializer.Deserialize, JsonSerializer.Serialize18
Rust library serde_json::from_str, serde_json::to_string19
Java library Gson fromJson, toJson; Jackson ObjectMapper20
C++ library nlohmann/json json::parse, dump21
Kotlin library kotlinx.serialization Json.decodeFromString, Json.encodeToString24
PowerShell stdlib ConvertFrom-Json, ConvertTo-Json25
SQL native JSON functions; in SQLite, json, json_extract and ->>22
Bash library the command-line tool jq23
C library cJSON, Jansson, json-c

The tool jq reads JSON from standard input, applies a filter and writes JSON. For example, jq .id prints the member id of each input value.23 Most languages also have a streaming API that reads tokens one at a time, for texts that are too large for memory.

JSON Schema

JSON Schema is a vocabulary to describe the shape of JSON data, written in JSON. A schema can say that a value is an object, that it has the member id, that id is an integer and that tags is an array of unique strings. A validator checks a value against a schema and reports each violation. The draft 2020-12 has two documents: Core, which defines the schema structure and references, and Validation, which defines keywords such as type, required, minimum, pattern and enum.1415 Code generators, API description formats and editors use the schemas.

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. ECMA-404, The JSON data interchange syntax, 2nd edition, December 2017, the whole standard
  3. T. Bray (Ed.), RFC 7493: The I-JSON Message Format, March 2015, 2.1 Encoding and Characters; 2.2 Numbers; 2.3 Object Constraints; 4 Recommendations for Protocol Design
  4. A. Rundgren, B. Jordan, S. Erdtman, RFC 8785: JSON Canonicalization Scheme (JCS), June 2020, 3.1 Creation of Input Data; 3.2 Generation of Canonical JSON Data
  5. Introducing JSON, json.org, the first paragraph and the grammar diagrams
  6. Douglas Crockford, The JSON Saga (transcript of the talk), the first message, the quoted keys, the site json.org and the removal of comments
  7. D. Crockford, RFC 4627: The application/json Media Type for JavaScript Object Notation (JSON), July 2006, the header and the abstract
  8. T. Bray (Ed.), RFC 7159: The JavaScript Object Notation (JSON) Data Interchange Format, March 2014, the header (obsoletes RFC 4627)
  9. ECMA-262, ECMAScript 2026 Language Specification, 25.5 The JSON Object; 6.1.6.1.20 Number::toString
  10. TC39 proposal, Subsume JSON (JSON superset), the README
  11. The JSON5 Data Interchange Format, version 1.0.0, March 2018, 1 Introduction; 1.2 Summary of Features
  12. JSON Lines, the three requirements and the file extension
  13. N. Williams, RFC 7464: JavaScript Object Notation (JSON) Text Sequences, February 2015, the abstract; 2.2 JSON Text Sequence Encoding
  14. JSON Schema, A Media Type for Describing JSON Documents, draft 2020-12, the whole document
  15. JSON Schema Validation, A Vocabulary for Structural Validation of JSON, draft 2020-12, 6 A Vocabulary for Structural Validation
  16. The Python Standard Library, json, Python 3.14, Basic Usage; Standard Compliance and Interoperability
  17. Go standard library, package encoding/json, func Unmarshal; func Marshal; Decoder.UseNumber
  18. .NET documentation, JSON serialization and deserialization in .NET, the overview
  19. serde_json 1.0.154 documentation, the crate documentation, Value and from_str
  20. Gson, the README
  21. JSON for Modern C++ (nlohmann/json) documentation, the home page and the features
  22. SQLite, JSON Functions And Operators, the overview and the list of functions
  23. jq manual, the invocation and the basic filters
  24. Kotlin documentation, Serialization, the JSON section
  25. PowerShell documentation, ConvertFrom-Json, the description and the parameters

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)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/Z3QSNB/text.yaml