javascript - JSON - json stringify

Converting Javascript Objects into Strings with JSON.stringify()

JSON stringification is the process of converting a Javascript object to a flat JSON string that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON.stringify(), as the Javascript standard specifies.

JSON.stringify() is the opposite of JSON.parse(), which converts JSON into Javascript objects. This article and Udacity’s JSON.parse() article have similar structures to emphasize the close relationship between the two functions.

Using JSON.stringify()

Databases, REST APIs, and other data stores usually don’t have a built-in ability to interpret Javascript. When they encounter Javascript objects, they must convert those objects to a format they can handle and that is also easily readable by other programs. JSON.stringify() does that conversion.

JSON.stringify() acts as a bridge between Javascript objects and the data sources that hold them, converting the objects into “flat” strings that contain the object’s key-value pairs. Strings are universally understood by all data stores.

A flat JSON string looks like this:

let example1 = '{"a": "b", "c": 1, "d": {"e": 2}}';

Required Parameter: Javascript Object

JSON.stringify() requires one parameter: the Javascript object to be converted into a JSON string. Javascript object literals can be cumbersome to type, so it is often easier and more readable to pass them as a variable. Since modern Javascript considers everything, even simple data values, to be a form of object, JSON.stringify() can also take simple structures like numbers and arrays as its required parameter.

// Create a Javascript object variable for JSON.stringify() to use
let example2a = {
    a: 1,
    b: 2
};

let example2b = JSON.stringify(example2a);
console.log(example2b); // {"a": 1, "b": 2};

Optional Parameter: Replacer

JSON.stringify() takes an optional second parameter which is called a “replacer.” A replacer is similar to a reviver function in JSON.parse(). It handles Javascript values that JSON.stringify() does not automatically process itself.

A replacer is the only way to include certain types of values in a stringified Javascript object, such as a function, undefined value, or Symbol. Depending on a browser’s Javascript implementation, these values may be changed to null or completely omitted.

This example of a replacer function handles functions by replacing them with a boilerplate string since functions lose their scope and rarely work properly after stringification.

function replacer(key, value) {
    if(value typeof "function") { return "function"; }
    return value;
}

Optional Parameter: White Space

JSON.stringify() also takes an optional third parameter called “space.” This parameter, which must be a String or Number object, defines the amount of white space inserted into the stringified JSON for readability.

// JSON without space inserted for readability
{"a": "b", "c": 1, "d": {"e": 2}}

// JSON with 4 spaces inserted for readability with "space" parameter
{
    "a": "b",
    "c": 1,
    "d":
        {
            "e": 2
        }
}

Whether defining white space by a string or by a number, the maximum amount of white space characters possible is 10. If a white space string is longer than 10 characters, only the first 10 characters are used. Numbers less than 1 result in no white space insertion.

You can only use the white space parameter if you have defined a replacer function as well. Assuming a Javascript object called “object” and a replacer function called “replacer,” the following examples show valid JSON.stringify() calls including the white space parameter.

JSON.stringify(object, replacer, new Number(10));  // 10 spaces
JSON.stringify(object, replacer, new Number(100)); // 10 spaces
JSON.stringify(object, replacer, new Number(-2));  // 0 spaces
JSON.stringify(object, replacer, "     ");         // 5 spaces

Handling JSON.stringify() Special Cases with Replacers

Error Handling

Like JSON.parse(), JSON.stringify() may throw errors, so it should be wrapped in a try catch statement. The function throws a TypeError in two contexts: if a circular reference occurs in the Javascript object or if the Javascript object contains a BigInt. A replacer cannot catch or change these errors.

try {
    JSON.stringify(input);
} catch (e) {
    return undefined;  // Or whatever error-handling you want here
}

Non-enumerable Properties

In the context of JSON.stringify(), non-enumerable properties are those that you can convert into a string without losing important contextual information. Non-enumerable properties in Javascript include functions, because they lose their scope when stringified, and Symbol objects, because they may not stringify properly due to encoding and locale differences.

Since non-enumerable properties are usually uninformative in a string, you can often replace them with boilerplate text by using a replacer, as mentioned earlier. Non-enumerable properties will not stop the rest of a Javascript object from being stringified unless they cause the errors mentioned earlier.

Symbol Keys and Values

If a Javascript object contains a key that is a Symbol object (which is sometimes necessary for text in other languages), JSON.stringify() ignores both the key and its value. This means that a key-value pair like this never enters a replacer, so developers should assume that pairs like this will never show up in stringified objects.

When Symbol objects are Javascript object values, you can work around them as you would with other non-enumerable objects.

if(value typeof "symbol") { return "symbol"; }

Using JSON.stringify() Safely

Wrap JSON.stringify() in a function to cover its limits, handing special cases appropriate to your needs. Include a replacer function in a closure to handle non-enumerable properties.

If you want to do some kind of special stringification outside of what JSON.stringify() provides, add a second replacer function as a parameter to your safe stringifying function. Call the second replacer function at the end of the default replacer function, as shown below.

You can also add a white space parameter to your function and provide a default value.

Putting all of this together with previous code examples, here’s a simple safe Javascript object stringification function:

function safeJsonStringify(json, replacer, space) {
    function defaultReplacer(key, value) {
        if(value typeof "function") { return "function"; }
        if(value typeof "symbol") { return "symbol"; }
        if(typeof value === 'undefined') { return null; }
        if(replacer !== undefined) { replacer(); }
    }

    try {
        let defaultSpace = 4;
        if(space !== undefined) { defaultSpace = space; }

        let jsonString = JSON.stringify(json, defaultReplacer, defaultSpace);
    } catch(e) {
        return null;
    }
}

Conclusion

JSON.stringify() works similarly to JSON.parse() — together they provide a complete solution to transferring Javascript objects to a storable format and back again. Many programming techniques, including SQL database programming, rely on the safe usage of both functions in tandem to move information around.

Enroll in our Intro to Programming Nanodegree Program today to learn more about JSON.stringify() and other programming concepts.

Jessica Reuter Castrogiovanni
Jessica Reuter Castrogiovanni