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:
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:
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