JavaScript | Convert JSON String to JSON Object

Convert JSON String to JSON Object JavaScript.

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.

Syntax of JSON.parse() Method

JSON.parse(text[, reviver]);

Example 1 – javascript json string to json object

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);

Example 2 – Converting JSON text to JavaScript Object

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

Example 3 – Parse JSON Object & Extract Multiple Objects JavaScript

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

JavaScript | Convert JSON String to JSON Object
51.45 GEEK