JavaScript, JSON Parse Method


How to parse JSON using JavaScript?

JSON is used to transfer data between web applications via REST APIs. To convert JSON string to object using JavaScript you can use a method called JSON.parse. Let take a look at an example :

let jsonStr = "{\"firstName\":\"jake\",\"lastName\":\"thomson\",\"age\":10,\"state\":\"Kerala\",\"district\":\"Kochi\"}";
let jsonObj = JSON.parse(jsonStr);
console.log('JSON obj ', jsonObj);
// Output
{
    "firstName": "jake",
    "lastName": "thomson",
    "age": 10,
    "state": "Kerala",
    "district": "Kochi"
}

It has an optional callback method using which you can transform or delete an existing property in a JSON object. Here is an example:

let jsonStr = "{\"firstName\":\"jake\",\"lastName\":\"thomson\",\"age\":10,\"state\":\"Kerala\",\"district\":\"Kochi\"}";
let newJsonObj = JSON.parse(jsonStr, (key, value) => {
    if(key == "age") return value + 2;
    return value;
})
console.log('New json obj ', newJsonObj);
// Output
{
    "firstName": "jake",
    "lastName": "thomson",
    "age": 12,
    "state": "Kerala",
    "district": "Kochi"
}

As seen in the above code, inside the callback function we are incrementing the age by 2. You can also remove a property from the JSON object by returning undefined. Here is an example:

let jsonStr = "{\"firstName\":\"jake\",\"lastName\":\"thomson\",\"age\":10,\"state\":\"Kerala\",\"district\":\"Kochi\"}";
let newJsonObj = JSON.parse(jsonStr, (key, value) => {
    if(key == "age") return undefined;
    return value;
})
console.log('New json obj ', newJsonObj);
// Output
{
    "firstName": "jake",
    "lastName": "thomson",
    "state": "Kerala",
    "district": "Kochi"
}

As seen in the above code, you returned undefined for key age and it got removed from the resulting JSON object.