Well formed JSON stringify JavaScript: ES10/2019

JavaScript , , , 0 Comments

In this article, we will learn the new well-formed JSON stringify JavaScript method introduced in ES10/2019 with examples and comparisons with the old one.

RFC 8259 section 8.1 requires JSON text exchanged outside the scope of a closed ecosystem to be encoded using UTF-8, but JSON.stringify can return strings including code points that have no representation in UTF-8 (specifically, surrogate code points U+D800 through U+DFFF). And contrary to the description of JSON.stringify, such strings are not “in UTF-16” because “isolated UTF-16 code units in the range D800₁₆..DFFF₁₆ are ill-formed” per The Unicode Standard, Version 10.0.0, Section 3.4 at definition D91 and excluded from being “in UTF-16” per definition D89.

Read more about proposal

Previously JSON.stringify method has been defined to return unformed  Unicode strings if there are any lone surrogates in the input, for example below:

// '"�"'

But now, because Lone UTF-16 surrogates cannot be encoded as UTF-8, that’s why the proposal, well-formed JSON.stringify changed the JSON.stringify so that it generates escape sequences for lone surrogates, making its output valid Unicode (and representable in UTF-8) for example below:

// '"\\ud800"'

As you saw above the new JSON stringify JavaScript method returns the valid stringified Unicode.

Note that JSON.parse(stringified) still produces the same results as before.

This feature is a small fix that was long overdue in JavaScript. It’s one less thing to worry about as a JavaScript developer 😀


Non-BMP characters still serialize to surrogate pairs.

// → '"𝌆"'
// → '"𝌆"'

Unpaired surrogate code units will serialize to escape sequences.

// → '"\\udf06\\ud834"'
// → '"\\udead"'

Browser Support

Well-formed JSON.stringify()72?64Yes?

Thanks for reading, Share with love.

Spread the love

Leave a Reply

Notify of