Kieran Hunt

Will it JSON?

✦ 2023-11-09

It seems like a pretty common misconception that the only valid JSON document (archive) is one who’s top-most value is an object. Maybe something like:

{ // ← it has to start with this
  "foo": "bar",
  "baz": ["qux"]
}

But that’s not true. The following are all valid JSON documents:

object

{ "foo": "bar" }

JSON.stringify({ "foo": "bar" });
// '{"foo":"bar"}'

JSON.parse('{"foo": "bar"}');
// Object { foo: "bar" }

array

["foo"]

JSON.stringify(["foo"]);
// '["foo"]' 

JSON.parse('["foo"]');
// Array [ "foo" ]

string

"bar"

JSON.stringify("bar");
// '"bar"' 

JSON.parse('"bar"');
// "bar"

number

100

JSON.stringify(100);
// '100' 

JSON.parse('100');
// 100

"true"

true

JSON.stringify(true);
// 'true' 

JSON.parse('true');
// true

"false"

false

JSON.stringify(false);
// 'false' 

JSON.parse('false');
// false

"null"

null

JSON.stringify(null);
// 'null' 

JSON.parse('null');
// null