You are on page 1of 2

JSON

 JSON: JavaScript Object Notation.
 JSON is syntax for storing and exchanging data.
 JSON is text, written with JavaScript object notation
 JSON is a lightweight data-interchange format
 JSON is "self-describing" and easy to understand
 JSON is language independent.

Syntax:
 Data is in name/value pairs
 Data is separated by commas
 Curly braces hold objects

Example: JSON file (It is a text file):


{
"name": "John", 
"age": 31,
"city": "New York"
};

Example for Java Script Object: (Here employee is a java script object)

Var employee = {name: "John", age: 31, city: "New York"};

Java Script Data


Object

Access Java script object:

Employee.name; or Employee [“name”];

Methods of Function files:

1. Stringify(Java script object)


2. Parse(JSON file)
Stringify()
Java Script
Json File
Object
Parse()

Sending Data (Java script object convert into JSON file)

var myObj = {name: "John", age: 31, city: "New York"}; // java script object


var myJSON = JSON.stringify(myObj); // convert into JSON file

Receiving Data: (JSON file convert into Java Script object file)

var myJSON = '{"name":"John", "age":31, "city":"New York"}';


var myObj = JSON.parse(myJSON);
Data Types:

 a string ex: { "name":"John" }


 a number ex: { "age":30 }
 an object (JSON object) ex: {"employee":{ "name":"John", "age":30, "city":"New York" }}
 an array ex: {"employees":[ "John", "Anna", "Peter" ]}
 a Boolean ex: { "sale":true }
 null ex: { "middlename":null }

HTTP Request:

 You can request JSON from the server by using an AJAX request

 The response from the server is written in JSON format, you can parse the string into a
JavaScript object.

Json file (json_demo.txt)

{"name": "John", "age": 31, "city": "New York"};

Html file (myhtml.html)

<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();
</script>
</body>
</html>

Output:

John

You might also like