JSON.stringify, JSON.parse, and Escaping

See the difference between JSON text, a JSON string literal, and a parsed value with concrete examples.

JSON.stringify converts a JavaScript value to JSON text. JSON.parse reads JSON text and returns a JavaScript value. Escaping is the narrower task of representing characters inside a JSON string literal.

One object, three representations

Suppose a program has the value { name: 'Alex' }. This is JavaScript object notation, not JSON text. JSON.stringify({ name: 'Alex' }) returns the string of characters {"name":"Alex"}. Those characters form a valid JSON document representing an object.

If you need to place that entire document inside a JSON string, the string literal is "{\"name\":\"Alex\"}". The outer quotes and backslashes belong to the encoded string, not to the object document.

Input Operation Result
hello Escape text "hello"
"hello" Unescape JSON string hello
{"name":"Alex"} Stringify JSON document "{\"name\":\"Alex\"}"
"{\"name\":\"Alex\"}" Unstringify document {"name":"Alex"}

Try these modes in the JSON escape and unescape tool. Its stringify document mode validates the source as JSON, then wraps its exact text as a string. In JavaScript, JSON.stringify(JSON.parse(text)) may normalize formatting and number representation instead.

Parsing failures

JSON.parse('{name:"Alex"}') throws because the property name is not in double quotes. JSON.parse('"hello"') returns the plain string hello; JSON.parse('hello') throws because bare hello is not JSON. The validator explains malformed JSON with a location.

Never use eval() to decode JSON. It executes JavaScript and accepts syntax that strict JSON does not. For the JSON grammar and escaping rules, see RFC 8259.

Already have valid JSON? Make it readable