Introduction
In this short tutorial we will learn how to parse a JSON string to a JavaScript object.
The code
We will start by defining a string literal containing a valid JSON object. This JSON object will be very simple, containing two properties:
- name: a string;
- age: a number.
const jsonString = `{ "name": "Todd", "age": 20 }`;
Then, to parse this string to a JavaScript object, we simply need to call the parse method on the JSON built-in object. As input, this method receives the JSON string and, as output, it returns the corresponding JavaScript object
const obj = JSON.parse(jsonString);
To confirm the object was correctly parsed, we will print its properties to the console.
console.log(obj.name); console.log(obj.age);
Upon running the previous code, we should get an output similar to figure 1. As can be seen, the values of both properties of the object were correctly printed.
