Parse in JavaScript - Parse JSON - Tech tutorial - Udacity Instructor Series

Parsing JSON in JavaScript.

When developing web apps, you’ll often come across a data format known as JSON, or JavaScript Object Notation. Making HTTP requests to a REST API, for example, will more than likely return a JSON response, and it will be up to you as the developer to both parse and perform operations on that response.

In this post, we’ll explore what JSON is, as well as how to convert JSON into formats for use in a JavaScript environment.

JSON or JavaScript?

An object (literal) in JavaScript is a collection of key-value pairs, where values can be of many different data types (e.g., numbers, strings, booleans, arrays, or even another object). Here’s an example of a simple book object in JavaScript:

const book = {
 name: "Invisible Man",
 author: "Ralph Ellison",
 published: 1952,
 read: false,
};

For the most part, both JSON and JavaScript object representations of that same data are quite similar. A strict requirement for JSON, however, is that keys need to be wrapped in double quotation marks. Here’s what the same book data looks like as a JSON object:

{
 "name": "Invisible Man",
 "author": "Ralph Ellison",
 "published": 1952,
 "read": false
}

Note that the name, author, published, and read properties are each enclosed by double quotes (the use of single quotes is invalid JSON). In addition, JSON also restricts the use of any trailing commas for the last key-value pair in the collection.

However, the previous code snippet, as-is, is still perfectlyvalidJavaScript. Why is there still a need to convert JSON into a format readable by JavaScript (or any language, for that matter)?

JSON is a string.

Though it resembles JavaScript, JSON is actually text-based data. That is, JSON is a string. Before any data represented in JSON can be used in a JavaScript environment (Node or the browser), it first needs to be converted (i.e., deserialized) into a native object that JavaScript can understand.

Out of the box, JavaScript provides a global JSON object with methods for parsing and converting values to and from JSON. Let’s first take a look at how the JSON.parse() method allows us to convert a JSON string into a JavaScript object.

Syntax.

Here’s the full signature for JavaScript’s built-in parsing method:

JSON.parse(text, reviver)

The method takes in two parameters:

  • text, which is the serialized JSON string itself, and
  • reviver, which is an optional function that modifies (e.g., filters) the data before the function returns

If parsing is successful, the method returns a native JavaScript object. Consider the following example:

const book =
 '{"name": "Invisible Man", "author": "Ralph Ellison", "published": 1952, "read": false}';
 
const result = JSON.parse(book);

In order to provide valid JSON data as text to JSON.parse(), the JSON object must be wrapped in single quotes. As such, the entire collection of key-value pairs is represented as a string:

console.log(typeof book); // string

After successful parsing, the result is a regular JavaScript object:

console.log(typeof result); // object
console.log(result);
 
/*
{
 name: 'Invisible Man',
 author: 'Ralph Ellison',
 published: 1952,
 read: false
}
*/

And as such, we can access properties in the resulting object as we would with any JavaScript object:

 console.log(result.name); // "Invisible Man"
console.log(result.author); // "Ralph Ellison"
console.log(result.published); // 1952
console.log(result.read); // false

Now, what happens if we want to modify the incoming JSON data before returning it as a JavaScript object? This is where we can leverage the optional reviver function.

The reviver function.

Consider this example: let’s say that with the raw JSON book data, the read status of the book should be toggled. That is, before we work with that data in JavaScript, we first want all true statuses to be switched to false, and all false statuses to be switched to true. We can accomplish this by creating a reviver function to handle that data manipulation for us.

During the parsing process, the reviver function is called for each key-value pair in the JSON string. This way, we can execute any custom business logic we want on that data before it is returned in the JavaScript object.

We’ll first define the two parameters that the  JSON.parse() accepts: the text and the reviver.

const book =
 '{"name": "Invisible Man", "author": "Ralph Ellison", "published": 1952, "read": false}';
 
function toggleRead(key, value) {
 if (key === "read") {
   return !value;
 } else {
   return value;
 }
}

With these two parameters defined, we pass them into the parsing method:

const result = JSON.parse(book, toggleRead);

As the parsing function iterates through the JSON string, toggleRead() is called for each of the four key-value pairs in the book object. As such, the resulting value becomes:

console.log(result);
 
/*
{
 name: 'Invisible Man',
 author: 'Ralph Ellison',
 published: 1952,
 read: true
}
*/

Note that the read status has been toggled to its opposite value (i.e., from its original true value in the JSON string to false in the resulting JavaScript object).

Overall, the reviver function is a great spot to include custom business logic and other transformations on the JSON string being parsed into JavaScript.

Parsing a JSON array.

In addition to all the above, note that JSON.parse() can handle JSON arrays as well (an array is an object, after all):

const team =
'["Andy", "Peter", "Gabriella", "Jordy"]';
 
 
const result = JSON.parse(team);
 
console.log(typeof result); // object
 
console.log(result); // ['Andy', 'Peter', 'Gabriella', 'Jordy']

Further reading.

JSON is all over the web. It’s a data format that’s predictable, uniform, and easy to read and write. Since JSON is parsed and deserialized by each language into native objects in that language, you may also see JSON parsed into hashes in Ruby, dictionaries in Python, and so on. In the case of JavaScript, JSON is parsed through the built-in JSON.parse() method into JavaScript object literals.

Check out the resources below and explore the Intermediate JavaScript Nanodegree program to be on your way to mastering the most popular programming language in the world.

START LEARNING