Web Technology
Web Technology
BY: ANIRUDHA K K
1KS20CS005
JSON is a data serialization format, like XML. That is, it is used to
represent object data in a text format so that it can be transmitted from one
computer to another.
Many REST web services encode their returned data in the JSON data
format instead of XML. While JSON stands for JavaScript Object
Notation, its use is not limited to JavaScript.
It was originally designed to provide a lightweight serialization format to
represent objects in JavaScript.
While it doesn’t have the validation and readability of XML, it has the
advantage of generally requiring significantly fewer bytes to represent data
than XML.
• AN EXAMPLE OF HOW AN XML DATA ELEMENT WOULD BE REPRESENTED
IN JSON IS – {"ARTIST": {"NAME":"MANET","NATIONALITY":"FRANCE"}}
• In general JSON data will have all white space removed to reduce
the number of bytes traveling across the network. Square brackets
are used to contain the three painting object definitions: this is the
JSON syntax for defining an array
Using JSON in JavaScript
Since the syntax of JSON is the same used for creating objects in JavaScript, it is easy to make
use of the JSON format in JavaScript:
<script>
Var a={“artist”:{“name”:”Manet”,”nationality”:”France”}};
Var a =JSON.parse(text);
alert(a.artist.name + " " + a.artist.nationality);
The JSON information will be contained within a string, and the JSON.parse() function can be
used to transform the string containing the JSON data into a JavaScript object:
var text = '{"artist": {"name":"Manet","nationality":"France"}}’;
var a = JSON.parse(text);
alert(a.artist.nationality);
JavaScript also provides a mechanism to translate a JavaScript object into a JSON string: var text
= JSON.stringify(artist);
Using JSON in PHP
PHP comes with a JSON extension . Converting a JSON string into a PHP object is quite straightforward:
<?php
// convert JSON string into PHP object
$text = '{"artist": {"name":"Manet","nationality":"France"}}’;
$anObject = json_decode($text);
echo $anObject->artist->nationality; // convert JSON string into PHP associative array
$anArray = json_decode($text, true);
echo $anArray['artist']['nationality’];
?>
The json_decode() function can return either a PHP object or an associative array. Since JSON data is often coming
from an external source, we should check for parse errors before using it, which can be done via the json_last_error()
function:
<?php
// convert JSON string into PHP object
$text = '{"artist": {"name":"Manet","nationality":"France"}}’;
$anObject = json_decode($text);
// check for parse errors
if (json_last_error() == JSON_ERROR_NONE) {
echo $anObject->artist->nationality;
}
?>
To convert a PHP object into a JSON string, use the json_encode() function.
// convert PHP object into a JSON string
$text = json_encode($anObject);
THANK YOU