JSON: How does it work and what does it do?

Wonder how so much data transfer takes places over the internet? Well, Javascript object notation—a.k.a. JSON is the “something” that helps such transfers. It is referred to as the format for light-weight interchange of data. The main interchange format for data is XML but JSON is a far less complicated format used for light data.

 

While JSON was initially created for use with JavaScript so that the latter could access any remote data, it is also used with several other computer languages. The main reason why so many languages are inclined to use with JSON is because it is not dependent on any platform.

 

JSON aids several kinds of data types, including boolean, strings, array data, numbers, value pairs, curly-bracketed data as well as data that are separated by commas.

 

A few examples for JSON and XML:

{ “company”: Volkswagen, “name”: “Vento”, “price”: 800000}

XML:<car><company>Volkswagen</company><name>Vento</name><price>800000</pric

e></car>

 

The main structure of JSON structure is intuitive, and this makes it very easy to read. As a result, this can be mapped directly to main objects for domain in any programming language. JSON has gained more popularity because it is lightweight and has become a better alternative for XML.

 

The reason for this is:

  • XML has much more lines of code than what we seen in JSON.
  • JSON is also faster since it takes a longer time to parse software in XML.
  • However, JSON allows you to store only limited data formats such as numbers and text. On the other hand, XML has scope for storing any type of data format.

 

 

PHP code for creating JSON format using an array of PHP is:

$json_data = array

(‘id’=>1,’name’=>“mike”,’country’=>’usa’,“office”=>array(“microsoft”,“oracle”));

echo json_encode($json_data);

For decoding JSON data in PHP, the format is:

$json_string='{“id”:1,“name”:“mike”,“country”:“usa”,“office”:[“microsoft”,“oracle”]} ‘;

$obj=json_decode($json_string);

As for the $obj variable that comes with JSON data parsed in the PHP object, you may

use the code below-

echo $obj->name; //displays mike

echo $obj->office[0]; //displays Microsoft

 

CGurukul provides PHP Training in Delhi for freshers. Learn PHP from PHP Experts and become Corporate Ready.

Posted in Tech Tank
[fbcomments]

Courses We Offer

Become Drupal Expert in 50 hours

Course is designed for Individuals looking to become Drupal developers or those who already know Drupal basics want and to get better at it.