Create json object from string

We can use JSON.parse() or eval() function to create json object from string in javascript.

Using JSON.parse() function:

Syntax:

var obj = JSON.parse(textString);

Example:

<!DOCTYPE html>
<html>
<body>
 
<h2>Create json object from string.</h2>
 
<p id="testDemo"></p>
 
<script>
 var textString = '{"students":[' +
  '{"firstName":"Sandy","lastName":"Sethi" },' +
  '{"firstName":"Roxy","lastName":"Malik" },' +
  '{"firstName":"Sunil","lastName":"Antil" }]}';
 
 var obj = JSON.parse(textString);
 document.getElementById("testDemo").innerHTML =
 obj.students[0].firstName + " " + obj.students[0].lastName;
</script>
 
</body>
</html>
]}

Using eval() function:

Syntax:

var obj = eval ("(" + textString + ")");

Example:

<!DOCTYPE html>
<html>
<body>
 
<h2>Create json object from string.</h2>
 
<p id="testDemo"></p>
 
<script>
 var textString = '{"students":[' +
  '{"firstName":"Sandy","lastName":"Sethi" },' +
  '{"firstName":"Roxy","lastName":"Malik" },' +
  '{"firstName":"Sunil","lastName":"Antil" }]}';
 
 obj = eval ("(" + textString + ")");
 document.getElementById("testDemo").innerHTML =
 obj.students[1].firstName + " " + obj.students[1].lastName;
</script>
 
</body>
</html>
]}

 
Next Topic: How to access json object array in javascript?
Previous Topic: JSON format and data types.