How to create json object from string in javascript?

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.

Related Topics:

How to build java project using ant in eclipse?
JAXB marshalling – convert java object to xml example.
How to create pdf file in java using iText jar?
Generics class example.
OGNL in struts 2.
Hibernate One-to-One Mapping using xml.
Send inline image in email using JavaMail API.
Quartz 2 JobListener example.