views:

1110

answers:

9

Could you please tell me, what is the use of JSON (in Javascript and PHP). when we need a JSON method.

I read from the following link but, i didn't get any information regarding the JSON implementation on any project.

http://www.json.org/js.html

+14  A: 

JSON is a light-weight data-interchange format (think of it as XML on a diet). Basically any place where you can use XML for serializing data you can use JSON instead.

Andrew Hare
+3  A: 

JSON is just a data format. If you need to store or transport data that is no more complicated than a nested series of name-value pairs, whose values are supported by the JSON standard, then JSON might be the right data format for your project.

If your project had data storage/transport needs ;)

Peter Bailey
+4  A: 

Despite its name, one of the primary uses of the JSON format is in AJAX web development (though certainly not the only one). It is often preferred over the traditional XML for its light-weight syntax.

Noldorin
+2  A: 

JSON is relatively light-weight data exchange format (at least when compared to XML or HTML) and is most useful when exchanging small amounts of data between a web client and a web server/service.

However, it is not the best choice (although much better than XML) for exchanging large lists of data, due to its overhead per row exchanged.

Jeff Leonard
+3  A: 

JSON is data format used in the transmission of data. It's used primarily in Javascript AJAX calls.

JSON's structure is simply bracketed name:value pairs. Because of it's compact nature and simplicity it's a better structure for the transmission of relatively small datasets and things that can be grouped into name:value pairs.

For example:

A prototype.js Ajax call transforming and receiving JSON data:

my_prototype_class = Class.create();  
my_prototype_class.prototype = {
    initialize: function() { 
     this.myarray = new Array();
     //do initialization
    },      
    my_function: function(direction){  
     new Ajax.Request('/my/url.php', 
      {     
       method: 'post',
       parameters: {  name: value,
           myarray_data: this.myarray.toJSON()  },   
       onSuccess: function(transport) { 
        var response = transport.responseText.evalJSON();
        //handle response   
       },
       onFailure: function(){
        //handle failure
       }    
      });  
    }
} 
Event.observe(window, "load", function(){new my_prototype_class();}, false);

And using PHP you'd handle the request with something like this:

function my_php_handler()
{   
    #parse POST data
    $name = $_POST["name"]; 
    $myarray_data = $_POST["myarray_data"];

    #transform the data in some way

    #return encoded string
    echo json_encode($results);
}

Something like:

[{"myarray": [], "name": value}]

will get passed around in the http request/response. Data in this format is called JSON.

ascotan
+1  A: 

JSON is mostly used as a lightweight and more human readable alternative to XML in AJAX web apps.

Andrew Marsh
+2  A: 

I would suggest using JSON if you have the need of manipulating the retrieved data (i.e. through an Ajax call in your browser) with JavaScript code. In such a case JSON is very comfortable since you can directly load it into your JavaScript and use it (therefore Java Script Object Notation => JSON). This is called deserialization of a JSON string in JavaScript objects. It can be done by using eval(), which however - I read - poses some security issues, wherefore some JSON (de)serializer should be used.

As described on the page you mentioned you have some JSON string like

{"bindings": [
        {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
        {"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
        {"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
    ]
}

which is sent over the network, initiated by some of Ajax call on the client where then a callback is invoked like (i.e. in .Net)

function onSuccess(result){
  var myObj = Sys.Serialization.JavaScriptSerializer.deserialize(result, false);
  myObj.bindings[0].ircEvent...
}

The advantage is just the easy (de)serialization together when using JavaScript, mostly on web development with Ajax. Otherwise I'd not really use JSON but rather rely on XML since for desktop apps there are really powerful parsing libraries.

Juri
+1  A: 

All of the other answers are great, but perhaps the simplest explanation for your specific case (JavaScript + PHP): JSON is the easiest way to translate a JavaScript object into a PHP associative array or object (and vice-versa).

Take a look at json_encode() and json_decode() for the PHP side of things. On the JavaScript side, a simple eval() is the easiest (but least-safe!) way to get an object out of a JSON string, but your library of choice will certainly have functions to take care of this for you, and if you're targeting newer browsers you can use the ECMAScript 5 JSON object.

Matt Kantor
+2  A: 

JSON is a great format for passing data back and forth between Javascript and PHP. My most common use is for status messages.

Here's some Javascript for doing a Ajax query to a small PHP script.

    new Ajax.Request('dostuff.php', {
        method:  'get',
        parameters:  {'param1':  'this is param 1'},
        onSuccess:  function(response, jsonHeader){
          if(jsonHeader['status'] == 'Success'){
            //Everything is OK, do stuff
          }else{
            alert(jsonHeader['status']);
          }
        },
        onFailure:  function(){
            alert('Fail!');
        }
    });

Then, on the PHP side, you can have something like this:

    $jsonHeader = array();

    if($_REQUEST['param1'])
    {
      echo '<p>You passed ' . $_REQUEST['param1'] . '</p>';
      $jsonHeader['status'] = 'Success';
    }else
    {
      $jsonHeader['status'] = 'Failed because the request was invalid';
    }

    if(is_array($jsonHeader) and sizeof($jsonHeader) > 0)
    {
      header('X-JSON: (' . json_encode($jsonHeader) . ')');
    }

The neat thing is that Prototype automatically decodes the X-JSON header that PHP is creating.

The end result is that the jsonHeader argument of the onSuccess method in Javascript is automatically converted into an array that's the same data as the $jsonHeader array in PHP

Mark Biek