FrontendDeveloper.in

ECMAScript question detail

JSON Improvements

JSON is used as a lightweight format for data interchange(to read and parse). The usage of JSON has been improved as part of ECMAScript specification. Basically there are 2 important changes related to JSON.

  1. JSON Superset

Prior to ES2019, ECMAScript claims JSON as a subset in JSON.parse but that is not true. Because ECMAScript string literals couldn’t contain the characters U+2028 (LINE SEPARATOR) and U+2029 (PARAGRAPH SEPARATOR) unlike JSON Strings. If you still use those characters then there will be a syntax error. As a workaround, you had to use an escape sequence to put them into a string.

eval('"\u2028"'); // SyntaxError

Whereas JSON strings can contain both U+2028 and U+2029 without producing errors.​

console.log(JSON.parse('"\u2028"')); // ''

This restriction has been removed in ES2019. This simplifies the specification without the need of separate rules for ECMAScript string literals and JSON string literals.

  1. Well Formed JSON.Stringify(): Prior to ES2019, JSON.stringify method is used to return unformed Unicode strings(ill-formed Unicode strings) if there are any lone surrogates in the input.
console.log(JSON.stringify("\uD800")); // '"�"'

Whereas in ES2019, JSON.stringify outputs escape sequences for lone surrogates, making its output valid Unicode and representable in UTF-8.

console.log(JSON.stringify("\uD800")); // '"\ud800"'
Back to all ECMAScript questions
Get LinkedIn Premium at Rs 399