JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON.parse(), as the Javascript standard specifies.

Using JSON.parse()

Javascript programs can read JSON objects from a variety of sources, but the most common sources are databases or REST APIs. A JSON object read from these sources enters a Javascript program in a “flat” string format that contains the object’s key-value pairs.

To create a valid string variable, you must surround the JSON string with single quotes.

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

JSON.parse() requires one parameter: the flat JSON string to be converted into a JSON object. JSON.parse() takes the flat JSON string directly or as a Javascript variable. Passing variables is easier and more readable than passing in a long flat JSON string.

JSON.parse('{"a", "b", "c", 1}');
let flatJSON2 = '{"a": "b", "c": 1, "d": {"e": 2}}';
JSON.parse(flatJSON2);

JSON.parse() takes an optional second parameter which is called a “reviver.” A reviver is a function that converts the JSON data that JSON.parse() cannot process by itself. This reviver function example handles undefined values:

let flatJSON3 = ‘{“a”: “b”, “c”: 1, “d”: {“e”: 2}}’;
let reviver = function(key, value) {
    if(typeof value === 'undefined') { return null; }
;

let parsed = JSON.parse(flatJSON3, reviver);

Revivers convert empty values and complex objects into valid Javascript objects. The next section goes into the specifics of how this is done with common examples.

JSON.parse() itself cannot execute functions or perform calculations. JSON objects can only hold simple data types and not executable code.

If you force code into a JSON object with a string, you must use the Javascript eval() function to convert it into something the Javascript interpreter understands. This process is prone to error and often causes problems with the converted code’s scope.

Revivers have the specific purpose of converting string data into valid Javascript types. You should make conversions within reviver functions as simple as possible. In rare cases, a specialized conversion might require a lot of calculations.

Handling JSON.parse() Special Cases with Revivers

Error Handling

Improperly-formatted data passed to JSON.parse() raises an error, stops processing, and returns no processed data, even if the rest of the JSON is correct. If an error occurs, never assume that JSON.parse() returns a specific value.

Depending on how you write your program, an error could stop the rest of your Javascript code from executing. Wrap calls to JSON.parse() in a try catch statement so you can explicitly specify what happens if parsing fails.

try {
    JSON.parse(input);
} catch (e) {
    return undefined; // Or whatever action you want here
}

Array Data

JSON.parse() converts array data into a Javascript array. The array data must be a valid JSON string.

This is an uncommon use for JSON.parse(). It’s easier to declare an array in code instead of going through JSON first. Declare arrays inside your Javascript program whenever possible.

Dates

Dates are not a valid JSON type. Converting strings of a particular format into a Javascript date type is a common extra step after using JSON.parse(). Several examples are shown below.

A reviver function that converts strings to dates may look like this, if using ISO standard date format:

function reviver(key, value) {
    if (value.match(/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/)) {
        return new Date(value);
    }
}

The Javascript Date object translates various string formats into dates. Always check whether the resulting date makes sense, even if the Date object “understood” its format. Here’s an example of a string conversion that results in an invalid real-world date:

// Converted to valid date: 02/16/2021
let date1 = JSON.parse('{"test": "2021-02-16"}');

// Converted to invalid date: 02/30/2021
let date2 = JSON.parse('{"test": "2021-02-30"}');

Empty Values

Null values and empty strings (“”) are valid JSON values, but the state of being undefined is not valid within JSON. JSON.parse() will fail if it encounters an undefined value.

Searching for undefined values in a JSON string is a possible workaround for this problem, but be careful not to match any instances of the word “undefined” in a string. A better solution is to search for and replace the undefined value with a similar empty value type:

let parsedVal = (typeof value === 'undefined') ? null : value;

Using JSON.parse() Safely

Wrap JSON.parse() in a function to cover its limits, handing special cases appropriate to your needs. Include a reviver function in a closure to handle common data conversion needs.

When you need more specialized data conversion than your default reviver function can handle, add a second reviver function as a parameter to your safe parsing function. Call the second reviver function at the end of the default reviver function.

Putting all of this together with previous code examples, here’s a simple safe JSON parsing function:

function safeJsonParse(json, reviver) {
    function defaultReviver(key, value) {
        if (value.match(/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/)) {
            return new Date(value);
        }

        if(typeof value === 'undefined') { return null; }
        if(reviver !== undefined) { reviver(); }
    }

    try {
        let json = JSON.parse(json, defaultReviver);
    } catch(e) {
        return null;
    }
}

Conclusion

JSON.parse() is a crucial method for converting JSON data in string form into Javascript objects. It is possible to convert simple or complex objects, but you should never convert calculations or code, like for loops.

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

Start Learning