Where/when we use JSON?

2020-05-19 15:40发布

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

9条回答
我命由我不由天
2楼-- · 2020-05-19 16:00

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.

查看更多
Emotional °昔
3楼-- · 2020-05-19 16:08

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.

查看更多
4楼-- · 2020-05-19 16:09

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.

查看更多
Rolldiameter
5楼-- · 2020-05-19 16:09

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 ;)

查看更多
祖国的老花朵
6楼-- · 2020-05-19 16:11

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.

查看更多
The star\"
7楼-- · 2020-05-19 16:18

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

查看更多
登录 后发表回答