Untitled
Untitled
Untitled
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.
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);
<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.