Parsing/Building JSON in Javascript
Example for building/parsing JSON in Javascript
Below example illustrate the client side building and parsing of JSON Object using Javascript code.,
A JSON format String needs to be created for field and value, and we can convert the String to JSON Object.
All current browsers have built in JSON support to create a native JSON Object.
Building JSON Object in Javascript:
<html>
<body>
<h2>Building JSON Object from JSON String.</h2>
<p id="jsonObj"></p>
<script>
var objStr = { names : "testjsonuser",
actions : "IllustrateJSONObjectInScript",
logincount : 2
};
var jsonObject = JSON.stringify(objStr);
document.getElementById("jsonObj").innerHTML = jsonObject;
</script>
</body>
</html>
</code>
Result:
{"names":"testjsonuser","actions":"IllustrateJSONObjectInScript","logincount":2}
We could see the result displays the JSON Object., and it has string field printed with double quotes.
The java Object is created with only name value pairs in objStr field.
Then the string value is converted to JSON Object., and printed in paragraph Element Object
Parsing JSON Object in Javascript
<!DOCTYPE html>
<html>
<body>
<h2>Parsing JSON Object In Javascript</h2>
<p id="demo"></p>
<script>
var objStr = { names : "testjsonuser2",
actions : "IllustrateJSONObjectInScript",
logincount : 2
};
var jsonObject = JSON.stringify(objStr);s
// Parsing JSON Object in Javascript..,
var obj = JSON.parse(jsonObject);
document.getElementById("demo").innerHTML = "names:" + obj.names + ",actions: " + obj.actions + ",logincount: " + obj.logincount;
</script>
</body>
</html>
Result:
names:testjsonuser2,actions: IllustrateJSONObjectInScript,logincount: 2
The JSON Object created can be parsed using the field name present in JSON Object.
The "names", "actions" and "logincount" values is displayed by parsing the object jsonObject.