What is a JSON-safe object?

Viewed 3222

In Kyle Simpson's book You Don't Know JS: this & Object Prototypes, he writes this on the subject of how to duplicate an object:

One subset solution is that objects which are JSON-safe (that is, can be serialized to a JSON string and then re-parsed to an object with the same structure and values) can easily be duplicated with:

var newObj = JSON.parse( JSON.stringify( someObj ) );

Of course, that requires you to ensure your object is JSON safe. For some situations, that's trivial. For others, it's insufficient.

What is a "JSON-safe" object? I ran a few tests with JavaScript and so far most things (arrays, numbers, strings, objects) can be duplicated using the above line, except for methods (foo.bar), when trying to duplicate a method, undefined is inserted in the method's place in the duplicated object.

1 Answers

To get foo<=> JSON.parse(JSON.stringify(foo)) as true, we must be able to represent foo in the JSON format.

JSON only supports:

Number: a signed decimal number that may contain a fractional part and may use exponential E notation, but cannot include non-numbers like NaN. The format makes no distinction between integer and floating-point. JavaScript uses a double-precision floating-point format for all its numeric values, but other languages implementing JSON may encode numbers differently.


String: a sequence of zero or more Unicodecharacters. Strings are delimited with double-quotation marks and support a backslash escaping syntax.


Boolean: either of the values true or false


Array: an ordered list of zero or more values, each of which may be of any type. Arrays use square bracket notation with elements being comma-separated.


Object: an unordered collection of name/value pairs where the names (also called keys) are strings. Since objects are intended to represent associative arrays,[12] it is recommended, though not required,[13] that each key is unique within an object. Objects are delimited with curly brackets and use commas to separate each pair, while within each pair the colon ':' character separates the key or name from its value.


null: An empty value, using the word null


In javascript, the concept of JSON safe object basically refers to a javascript object that can be represented in the JSON format without any loss.

Related