Updated July 4, 2023
Introduction to JSON Parser
JSON parser parses the JSON string, which returns a JavaScript object. Parsing JSON converts the JSON string to a JSON object by following some specifications. So based on the JSON object content, the result can be either a string, map or array, etc.
Syntax:
JSON.parse(string, function)
Arguments ‘string’ is a required parameter where a string is written in JSON format.
Reviver function is an optional parameter that is used to transform results. If this reviver function returns a valid value, the item value gets replaced with a transformed value. If, in case, the reviver returns undefined, then the item is deleted.
For Example:
var obj = JSON.parse('{ "employeeName":"Amar", "age":36, "city":"Paris"}');
SyntaxError exception is thrown if the string to parse is not a valid JSON.
JSON syntax is subset of JS syntax.
Working of JSON Parser
Javascriptobject, a data type in JS with properties and value pairs defined, JSON is a data interchange formatter. A bunch of characters are formatted in various programs for easy communication, which returns an object corresponding to JSON text/ string.
For Example:
varjsonSample = ‘{“employeeName”: “Amar”}’;
varobj = JSON.parse(jsonStr);
console.log(obj.employeeName); // prints “Amar”
console.log(jsonSample.employeeName); // prints undefined
When we parse JSON, the string gets converted to a JSON object which can be used anywhere in the code. Here, before parsing, it is a string, so data cannot be encoded. On parsing, it gets converted to a JS object, making it possible to access everywhere in the code.
Examples of JSON Parser
Given below are the examples mentioned:
Example #1
Code:
constjsonSample = '{"result":false, "count":24}';
constobj = JSON.parse(jsonSample);
console.log(obj.count);
console.log(obj.result);
console.log(JSON.parse('{}'));
console.log(JSON.parse('true'));
console.log(JSON.parse('"amar"'));
console.log(JSON.parse('[14, 45, "true"]'));
console.log(JSON.parse('null'));
//console.log(JSON.parse('[11, 22, 33, 44, ]'));
//console.log(JSON.parse('{"dob" : 34, }'));
//console.log(JSON.parse("{'age': 10}"));
Output:
Commented lines will give an error.
Example #2
Code:
<!DOCTYPE html>
<html>
<body>
<h2>Parsing from JSON String</h2>
<p id="demo"></p>
<script>
var txt = '{"employeeName":"Amar", "age":36, "city":"Paris"}'
varobj = JSON.parse(txt);
document.getElementById("demo").innerHTML = obj.employeeName + " of age " + obj.age + " lives in " + obj.city;
</script>
</body>
</html>
Output:
Example #3
Code:
<!DOCTYPE html>
<html>
<body>
<h2>Conversion of JSON string to date object</h2>
<p id="demo"></p>
<script>
varsampleText = '{"employeeName":"Amar", "dob":"1986-06-24", "city":"Paris"}';
varobj = JSON.parse(sampleText);
obj.dob = new Date(obj.dob);
document.getElementById("demo").innerHTML = obj.employeeName + " was born on " + obj.dob + " in " + obj.city;
</script>
</body>
</html>
Output:
So here, the Date function in Sretrieves the date of birth in IST Indian Standard Time. Date objects are not allowed in JSON, hence we write it as a string and then convert or parse it to an object.
Example #4
Code:
<!DOCTYPE html>
<html>
<body>
<h2>Conversion of JSON string to function using parse</h2>
<p id="demo"></p>
<script>
varsampleText = '{"employeeName":"Amar", "age":"function() {return 34;}", "city":"Paris"}';
varobj = JSON.parse(sampleText);
obj.age = eval("(" + obj.age + ")");
document.getElementById("demo").innerHTML = obj.employeeName + " of age " + obj.age() + " lives in " + obj.city;
</script>
</body>
</html>
Output:
As functions are not allowed, hence we include a function as a string and then parse it to a function. Functions lose their scope, eval() can be converted back to functions.
Example #5
Code:
<!DOCTYPE html>
<html>
<body>
<h2>Conversion of string to Date object using Reviver</h2>
<p id="demo"></p>
<script>
varsampleText = '{"employeeName":"Amar", "dob":"1986-06-12", "city":"Paris"}';
varobj = JSON.parse(sampleText, function (key, value) {
if (key == "dob") {
return new Date(value);
} else {
return value;
}
});
document.getElementById("demo").innerHTML = obj.employeeName + " was born on " + obj.dob + " and lives in " + obj.city;
</script>
</body>
</html>
Output:
Example #6
Code:
<!DOCTYPE html>
<html>
<body>
<h2>Using XMLHttpRequest to retrieve contents in a file</h2>
<p>The content is in JSON format, and can easily be converted to a JavaScript object</p>
<p id="demo"></p>
<script>
varxmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 &&this.status == 200) {
varmyObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();
</script>
<p>Open <a href="json_demo.txt" target="_blank">json_demo.txt</a></p>
</body>
</html>
Output:
On clicking josn_demo.txt, the below array is displayed. On using JSON.parse on an array, the parser returns a JavaScript array instead of an object.
Conclusion
As we have illustrated, all types of examples for JSON parsing, parsing a Date string to an object, function, array, and undefined values. While receiving data from a server, data is in the form of a string; sometimes, this string may contain multiple embedded fields. To use each field, we will not be able to use each in string format, and hence input string is parsed so that it becomes easy to use embedded fields in the string. We have seen what JSON is. parser means and how it works. The concept of JSON.parser is to read and interpret input data to an object. Hence parsing data would be useful to find out any embedded data inside the input string.
Recommended Articles
This is a guide to JSON Parser. Here we discuss the introduction to JSON Parser, working along with programming examples for better understanding. You may also have a look at the following articles to learn more –