JSON Basics

JSON Basics Introduction:

JSON stands for Java Script Object Notation, it’s a data transfer methodology like RSS and XML. It provides us syntax for transferring and saving data. It’s light weight and easier to use. The main feature of JSON is that it is language independent means any language can use JSON object and have JSON built in functions. JSON is fast and easy to use as compared to XML. We can fetch XML Document and XML DOM using JSON as well as we an store data in variables.

JSON as XML:

  • JSON is easily understandable as XML.
  • JSON is a hierarchical language as its values are within each other same is XML.
  • JSON is a platform independent language as XML, it is compatible with many languages because of platform independent behavior.
  • We can fetch JSON with XMLHttpRequest, as XML.

Difference between JSON and XML

  • XML uses end tags, whereas JSON doesn’t use.
  • JSON is shorter than XML.
  • We can easily understand and write JSON code, whereas XML is a bit difficult.
  • We can use arrays in JSON whereas we can’t use arrays in XML.

Example:

If we go through the above JSON example, we see there is an object like in JavaScript and this object contain an array and this array contain 3 more objects so that’s the reason we call it JavaScript Object Notation it looks much like JavaScript.

[ ] Square brackets are used for arrays in JSON.

{ } Curly brackets are used for objects in JSON.

JavaScript has a built-in function which is JSON.parse( ) which take a JSON command as a string and create its JavaScript object.

JSON has many things similar to XML like they both are self-describing, hierarchical, used by many programming languages and easy to learn and create etc.

JSON Structure:

It can use a name value pair like in associative arrays in Java Script and PHP.

“Name”: “value”

All the data elements are separated by commas.

The value of name value pair can be integers, string, double or float etc.

The entire JSON objects are written inside curly brackets.

eval():

This is a JavaScript function and used to convert a string in JavaScript into JavaScript Object, but this is an old technique nowadays we use JSON.parse() function instead of it. Using eval() makes your code vulnerable and it can be attacked easily.

JSON encode() and decode():

This function is mostly used in PHP when we have to send some data on user interface file using Ajax.

Supported JSON Browsers:

  • Chrome
  • Internet Explorer 8 or higher
  • Safari 4 or higher
  • Opera 10 or higher
  • Firefox 3.5 or higher

In case you want to give support to old browsers, you can download the library from Douglas Crockford‘s github.