Parse a JSON string to an object in JavaScript
This post will discuss how to parse a JSON string to an Object in JavaScript.
1. Using JSON.parse() function
JavaScript provides the native implementation of JSON.parse() method to parse the string. It returns the object corresponding to the given JSON string or throws a SyntaxError when the string is invalid JSON.
|
1 2 3 4 5 6 7 8 |
var obj = '{ "name": "Max", "age": 23 }'; var json = JSON.parse(obj); console.log(json); /* Output: { name: 'Max', age: 23 } */ |
To do the reverse, call the JSON.stringify() method.
|
1 2 3 4 5 6 7 8 9 10 |
var obj = '{ "name": "Max", "age": 23 }'; var json = JSON.parse(obj); // … var jsonString = JSON.stringify(json); console.log(jsonString); /* Output: {"name":"Max","age":23} */ |
2. Using jQuery
The jQuery library also has the $.parseJSON() method. This method is deprecated now, and it is recommended to use the native JSON.parse() method instead of parsing JSON strings.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
const { JSDOM } = require("jsdom"); const { window } = new JSDOM(); var $ = require("jquery")(window); var obj = '{ "name": "Max", "age": 23 }'; var json = $.parseJSON(obj); console.log(json); /* Output: { name: 'Max', age: 23 } */ |
That’s all about parsing a JSON string to an object in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)