Untitled

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

JSON

What is JSON?
- JSON stands for JavaScript Object Notation
- JSON is a lightweight data-interchange format
- JSON is language independent
- JSON is "self-describing" and easy to understand
- JSON is a syntax for storing and exchanging data.
- JSON is an easier-to-use alternative to XML.
JSON vs XML
JSON
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}

XML
<employees>
<employee>
<firstName>John</firstName> <lastName>Doe</lastName>
</employee>
<employee>
<firstName>Anna</firstName> <lastName>Smith</lastName>
</employee>
<employee>
<firstName>Peter</firstName> <lastName>Jones</lastName>
</employee>
</employees>
JSON - Evaluates to JavaScript
Objects
The JSON format is syntactically identical to the code for creating JavaScript
objects.

Because of this similarity, instead of using a parser (like XML does), a


JavaScript program can use standard JavaScript functions to convert JSON data
into native JavaScript objects.
JSON vs XML
Much Like XML Because

Both JSON and XML are "self describing" (human readable)


Both JSON and XML are hierarchical (values within values)
Both JSON and XML can be parsed and used by lots of programming languages
Both JSON and XML can be fetched with an XMLHttpRequest

Much Unlike XML Because

JSON doesn't use end tag


JSON is shorter
JSON is quicker to read and write
JSON can use arrays

The biggest difference is:

XML has to be parsed with an XML parser. JSON can be parsed by a standard JavaScript function.
Parsing JSON
JSON syntax is a subset of JavaScript syntax.

The JavaScript function JSON.parse(text) can be used to convert a JSON text into a JavaScript object:
var obj = JSON.parse(text);

Use the new JavaScript object in your page:


Example
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>

Using eval()

Older browsers without the support for the JavaScript function JSON.parse() can use the eval()
function to convert a JSON text into a JavaScript object:
Example
var obj = eval ("(" + text + ")");
json_encode() in PHP
PHP json_encode() function is used for encoding JSON in PHP. This function returns the JSON
representation of a value on success or FALSE on failure.

You might also like