JSON – An Overview

JSON stands for JavaScript Object Notation. It is a format for storing and exchanging data. It is based on a subset of the JavaScript Programming Language.

The file type for JSON files is “.json” and MIME type for JSON text is “application/json“.

Here are the characteristics of JSON:

  1. It is a lightweight data-interchange format.
  2. It is easy for humans to understand.
  3. It uses Javascript format but it is a text which makes it is completly language independent as text can be read and parsed by any programmng language.

JSON is based on two structures – Objects and Arrays.

Objects

  • It is an unordered set of name/value pairs.
  • An object begins with { (left brace) and ends with } (right brace).
  • The name value pairs are written as:
    • “name”:”value”
    • name is written in double quotes.
  • Name-value pairs separated by comma

Arrays

  • It is an ordered collection of values.
  • An array begins with [ (left bracket) and ends with ] (right bracket).
  • Values separated by comma.

Values

JSON Values in the Objects and Arrays can be:

  • string (in double quotes)
  • Number
  • Boolean (true or false)
  • null
  • object
  • array
 
JSON requires double quotes to be used around strings and property names. Single quotes are not valid.
 
JSON is a string, we need to convert it to javascript native object for accessing the JSON data. This is called parsing.
 
Converting javascript native object to JSON string is called stringification, you can use the javascript function JSON.stringify() for it.
 
You can validate JSON using an application like JSONLint.

 

Parsing JSON

 

1. JSON.parse()

You can use the javascript function JSON.parse(text) to convert a JSON text into a javascript object.


<script type="text/javascript">

var obj = JSON.parse(text);

</script>

2. eval()

For old browsers that do not support the JSON.parse() function, you can use the eval function to get the javascript object.


<script type="text/javascript">

var obj = eval ("(" + text + ")");

</script>

3. jQuery.parseJSON()


<script type="text/javascript">

var obj = jQuery.parseJSON(text);

</script>

 

Now you can access the “obj” object data as you do for any javascript object as shown below:


<!DOCTYPE html>
<html>
    <body>
        <h1>Parsing JSON String</h1>
        <script>
        var text = '{ "students": [' +
            '{ "name":"Greg" , "marks":{ "maths":80 , "science":90 } },' +
            '{ "name":"Yammi" , "marks":{ "maths":85 , "science":99 } },' +
            '{ "name":"Sam" , "marks":{ "maths":92 , "science":88 } }' +
            ']}';

        var obj = JSON.parse(text);
        var msg  = obj.students[1].name + " " + obj.students[1].marks.science;
        
        alert( msg );

        </script>
    </body>
</html>

 

Why should you prefer JSON over XML in AJAX applications?

 

  • For working with XML you need a XML parser but JSON can be parsed by a standard Javascript fuction
  • JSON is faster as compared to XML as it is shorter.

 

PHP sending JSON data in AJAX response

PHP “json_encode” function can be used to convert a PHP value to a JSON representation.


$fruits = array('Apple', 'Mango','Orange','Banana','Grapes');

echo json_encode($fruits);

Other JSON related functions in PHP are:

json_decode: It converts a JSON encoded string into a PHP variable.

json_last_error: It returns the last error (if any) occurred during the last JSON encoding/decoding.

 

Get JSON data with AJAX – prototype.js


new Ajax.Request('demo_ajax.php', {
                method:'get',
                requestHeaders: {Accept: 'application/json'},
                onSuccess: function(transport){
                    var jsondata = transport.responseText.evalJSON(true);
                }
            });

Here jsondata holds the parsed JSON data.

 

Get JSON data with AJAX – jQuery


$.ajax({
        type: 'GET',
        url: 'demo_ajax.php',
        contentType: "application/json",
        dataType: 'json',
        success: function(data)
        {
            $('#json-results').html(JSON.stringify(data));
            console.log(json);
        },
        error: function(e)
        {
            alert(e.message);
        }
    });

To make the above shorter, use $.getJSON()


$.getJSON("demo_ajax.php", function(result){
            $.each(result, function(key, value){
                $("div").append(key + " " + value);
            });
        });

Leave a Comment

Back to top