Parsing JSON in Javascript
In this article, you will learn how to parse the JSON in Javascript. AS, we know JSON is derived from the JavaScript object syntax, it is a characteristic decision to use as a data format in JavaScript. It is completely text-based. It follows the key-value data format that is ordinarily rendered in curly braces.
JSON (JavaScript Object Notation) is a lightweight, open standard, data-interchange format. It is easy to read and write for humans. It is used to generate data structures from user input and to transmit data between client web application and server or from server to client.
JSON.parse()
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
SyntaxJSON.parse(text[, reviver])
Here, the first parameter specifies the JSON string that needs to be parsed. The second parameter is optional, and that can be a function to modify the parsed JSON before returning. Let's show this method with an example -
<!DOCTYPE html>
<html>
<body>
<p id="getinfo"></p>
<script type="text/javascript">
var s = '{"first_name" : "Priska", "last_name" : "Kashyap", "location" : "Delhi", "phone" : "2389189281"}';
var obj = JSON.parse(s);
document.getElementById("getinfo").innerHTML =
"Name: " + obj.first_name + " " + obj.last_name + "<br>" +
"Location: " + obj.location + " " + "Phone: " + obj.phone;
</script>
</body>
</html>
JSON.stringify()
The JSON.stringify() function converts back a JavaScript object or value to a JSON string.
SyntaxJSON.stringify(value[, replacer[, space]])
Here, the value is the value to convert to a JSON string and replacer can be a function that alters the behavior of the stringification process. Here is the example -
<!DOCTYPE html>
<html>
<body>
<p id="getinfo"></p>
<script type="text/javascript">
var s = { first_name: "John", last_name: 30, location: "New York", phone: 2389189281};
var obj = JSON.stringify(s);
document.getElementById("getinfo").innerHTML = obj;
</script>
</body>
</html>
The variable obj is now a string, that we can easily send to the server.
Related Articles
How to convert associative array to XML in PHPGet Visitor Information by IP Address in PHP
Getting Document of Remote Address
Get Visitor's location and TimeZone
Get current visitor's location using HTML5 Geolocation API and PHP
JavaScript display PDF in the browser using Ajax call
jQuery loop over JSON result after AJAX Success
How to display PDF file in PHP from database
How to read CSV file in PHP and store in MySQL
Create And Download Word Document in PHP
PHP SplFileObject Standard Library
Simple File Upload Script in PHP
Sending form data to an email using PHP