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 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 used to generate data structures from user input and to transmit data between a client web application and a 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
Download and open PDF file using AjaxJavascript window location
How to reverse a number in Javascript
How to reverse string in Javascript
PHP script to read email inbox
How to retrieve data from database without refreshing page
Print specific part of webpage
Store Emoji character in MySQL using PHP
PHP Display PDF file from Database
Jquery ajax loop through data
Dynamically add/remove rows in html table using jquery
Submit form without page refresh using javascript
PHP Form Validation Tutorial
Google reCAPTCHA v3 PHP example
Select/deselect all checkboxes using Javascript
Javascript speech recognition example
Image popup on page load using HTML and jQuery
jQuery File upload progress bar with file size validation