JSON.parse() method is used to parse a JSON string and returns a JavaScript object.
Syntax
JSON.parse(text, reviver)
Parameters
- text(required): This is the string to be parsed as JSON.
- reviver(optional): A function that can transform the object values before they are returned. The reviver function is called for each member of the object. If a member contains nested objects, the nested objects are transformed before the parent object.
Return value
Returns Object, Array, Bool or null value corresponding to the given JSON text
Visual Representation
Example 1: How to Use JSON parse() method
Let us assume that we received the following text from a web server:
let obj = JSON.parse('{ "name":"David", "age":30, "city":"New York"}');
console.log(obj.city);
Output
New York
Example 2: Passing a reviver function
let jsonString = '{"name":"David", "age":30, "city":"New York"}';
let obj = JSON.parse(jsonString, (key, value) => {
if (key === "name") {
return value;
}
return value;
});
console.log(obj.name + " "+ obj.age);
Output
David 30
Browser Compatibility
- Google Chrome 3 and above
- Edge 12 and above
- Firefox 3.5 and above
- Safari 4 and above
- Opera 10.5 and above
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
Really nice tutorial dude !