JSON data types

The JSON format is widely used, especially to send and receive data from servers.

You can think of JSON as a way to send JavaScript data to the server but with some limitations.

In this article we are going to look at what data we can and cannot convert to JSON.

There are 6 data types in JSON:

  1. number
  2. boolean
  3. string
  4. null
  5. object
  6. array
JSON.stringify(1); // "1"
JSON.stringify(true); // "true"
JSON.stringify('hi'); // "\"hi\""
JSON.stringify(null); // "null"
JSON.stringify({ k: 1 }); // "{"k":1}" (backslashes omitted for brevity)
JSON.stringify([1, 2]); // "[1,2]"

And everything else outside the list above cannot be converted.

What cannot be converted to JSON data types

Dates. They are converted to a unix time string.

JSON.stringify(new Date()); // ""2021-05-01T16:13:44.277Z""

Functions, undefined and Symbols. They are ignored or converted to null.

const obj = { a: 1, f: function f() {}, u: undefined, s: Symbol(1) };
const arr = [1, function f() {}, undefined, Symbol(1)];

JSON.stringify(obj); // "{"a":1}"
JSON.stringify(arr); // "[1,null,null,null]"

The data structures WeakSet, WeakMap, Set and Map are converted to empty objects.

const ws = new WeakSet();
ws.add({ a: 1 });
const wm = new WeakMap();
const o = { a: 1 };
wm.set(o, 4);

const s = new Set([1]);
const m = new Map([[2]]);

const obj = {
  a: 1,
  b: ws,
  c: wm,
  d: s,
  e: m,
};

const arr = [1, ws, wm, s, m];

JSON.stringify(obj); // "{"a":1,"ws":{},"wm":{},"s":{},"m":{}}"
JSON.stringify(arr); // "[1,{},{},{},{}]"

Questions

What's JSON.stringify output?

JSON.stringify(1);

What's JSON.stringify output?

const ws = new WeakSet();
ws.add({ a: 1 });

JSON.stringify(ws);

What's JSON.stringify output?

JSON.stringify(new Set([10]));

What's JSON.stringify output?

const wm = new WeakMap();
const o = { a: 1 };
wm.set(o, 4);

JSON.stringify(wm);

What's JSON.stringify output?

JSON.stringify(new Map([[2]]));

What's JSON.stringify output?

JSON.stringify(true);

What's JSON.stringify output?

JSON.stringify('hi');

What's JSON.stringify output?

JSON.stringify(null);

What's JSON.stringify output?

JSON.stringify({ a: 1 });

What's JSON.stringify output?

JSON.stringify([4, 5]);

What's JSON.stringify output?

JSON.stringify(new Date(2021, 5, 5, 10, 10, 0, 0));

What's JSON.stringify output?

const obj = { a: 1, f: function f() {}, u: undefined, s: Symbol(1) };

JSON.stringify(obj);

What's JSON.stringify output?

JSON.stringify([1, function f() {}, undefined, Symbol(1)]);