You can use the javascript JSON.parse() method, to convert a JSON string into a JSON object. JSON is a commonly used data format for exchanging data between a server and web applications. It can be used in various ways and this tutorial is the purpose to show you the best examples for convert JSON string to a JSON object.
JSON.parse(text[, reviver]);
Let, if you have a json string like ” ‘‘{“name”:“John”, “age”:30, “city”:“New York”}’’ “, you want to convert into json object. You can use the below example:
var txt = '{"name":"John", "age":30, "city":"New York"}'
var obj = JSON.parse(txt);
console.log(obj);
If you want to extract the object value from the JSON object in javascript. So you can extract look like below:
var myStrObj = '{"name":"John", "age":30, "city":"New York"}';
var name = JSON.parse(myStrObj.name);
document.write('Result of the above code is:-' + name);
console.log(name);
Result of the above code is:-Name:-John
Now we will take the next example, here we will convert json string to objects and extract and display multiple objects:
var myStrObj = '{"name":"John", "age":30, "city":"New York"}';
var myJsonObj = JSON.parse(myStrObj);
document.write('Result of the above code is:-' + 'Name:-'+ myJsonObj.name + ' Age:-'+ myJsonObj.age);
Result of the above code is:-Name:-John Age:-30
#javascript #json