Use the JSON.parse() method to convert the JSON string to an object in JavaScript. If this method is used on JSON derived from an array, the method will return a JavaScript array, instead of a JavaScript object.
JSON.parse(jsonString);
Note: The JSON string must be well-formed for the JSON.parse()
method to work correctly. If the JSON string contains any syntax errors, the JSON.parse()
method will throw an error.
If you’re using jQuery just use:
jQuery.parseJSON( jsonString );
JSON string to object example
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script >
const jsonString = '{"name":"John","age":30,"city":"New York"}';
console.log(typeof(jsonString))
const obj = JSON.parse(jsonString);
console.log(obj);
console.log(typeof(obj))
</script>
</body>
</html>
Output:
![JSON string to object in JavaScript](https://i0.wp.com/tutorial.eyehunts.com/wp-content/uploads/2023/03/JSON-string-to-object-in-JavaScript.jpg?resize=468%2C197&ssl=1)
Using this method with JSON array
<!DOCTYPE html>
<html>
<body>
<script >
const text = '["Ford", "BMW", "Audi", "Fiat"]';
const myArr = JSON.parse(text);
console.log(myArr);
console.log(typeof(myArr))
</script>
</body>
</html>
Output:
![JavaScript Array as JSON](https://i0.wp.com/tutorial.eyehunts.com/wp-content/uploads/2023/03/JavaScript-Array-as-JSON.jpg?resize=421%2C202&ssl=1)
Do comment if you have any doubts or suggestions on this JS JSON string topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version