JSON Basics
Simply put, JSON can convert a set of data represented in a JavaScript object into a string, which can then be easily passed between functions, or in an asynchronous application passing a string from a WEB client to a server-side program. The string looks a bit odd (see a couple of examples later), but JavaScript is easy to explain, and JSON can represent a more complex structure than name/value pairs. For example, you can represent arrays and complex objects, not just simple lists of keys and values.
Simple JSON Example
In the simplest form, you can represent name/value pairs using JSON such as the following:
{"FirstName": "Brett"}
This example is very basic and actually takes up more space than the equivalent plain text name/value pair:
Firstname=brett
However, when multiple name/value pairs are strung together, JSON reflects its value. First, you can create records that contain multiple name/value pairs, such as:
{"FirstName": "Brett", "LastName": "McLaughlin", "email": "Brett@newInstance.com"}
In terms of syntax, this has no significant advantage over name/value pairs, but in this case JSON is easier to use and more readable. For example, it makes it clear that the above three values are part of the same record, and that the curly braces make some of these values a connection.
Array of values
When you need to represent a set of values, JSON not only improves readability, but also reduces complexity. For example, suppose you want to represent a list of people. In XML, many start and end tags are required, and if you use a typical name/value pair (like the name/value pair you see in the previous article in this series), you must create a proprietary data format or change the key name to a form such as Person1-firstname.
If you use JSON, you only need to group multiple records with curly braces together:
Copy CodeThe code is as follows:
{"People": [
{"FirstName": "Brett", "LastName": "McLaughlin", "email": "Brett@newInstance.com"},
{"FirstName": "Jason", "LastName": "Hunter", "email": "Jason@servlets.com"},
{"FirstName": "Elliotte", "LastName": "Harold", "email": "Elharo@macfaq.com"}
]}
It's not hard to understand. In this example, there is only one variable named people, and the value is an array of three entries, each of which is a person's record with first name, last name, and e-mail address. The above example shows how to combine records into a single value with parentheses. Of course, you can use the same syntax to represent multiple values (each value contains multiple records):
Copy CodeThe code is as follows:
{"Programmers": [
{"FirstName": "Brett", "LastName": "McLaughlin", "email": "Brett@newInstance.com"},
{"FirstName": "Jason", "LastName": "Hunter", "email": "Jason@servlets.com"},
{"FirstName": "Elliotte", "LastName": "Harold", "email": "Elharo@macfaq.com"}
],
"Authors": [
{"FirstName": "Isaac", "LastName": "Asimov", "Genre": "Science Fiction"},
{"FirstName": "Tad", "LastName": "Williams", "Genre": "Fantasy"},
{"FirstName": "Frank", "LastName": "Peretti", "Genre": "Christian Fiction"}
],
"Musicians": [
{"FirstName": "Eric", "LastName": "Clapton", "instrument": "Guitar"},
{"FirstName": "Sergei", "LastName": "Rachmaninoff", "Instrument": "Piano"}
]
}
Most notable here is the ability to represent multiple values, each of which in turn contains multiple values. However, it should also be noted that the actual name/value pairs in the record can differ between the different main entries (programmers, authors, and musicians). JSON is completely dynamic, allowing changes in the way the data is represented in the middle of the JSON structure.
There are no predefined constraints to follow when working with JSON-formatted data. So, in the same data structure, you can change the way you represent data, and you can even represent the same thing in different ways.
Using JSON in JavaScript
Once you've mastered the JSON format, it's easy to use it in JavaScript. JSON is a native JavaScript format, which means that working with JSON data in JavaScript does not require any special APIs or toolkits.
Assigning JSON data to a variable
For example, you can create a new JavaScript variable, and then assign the JSON-formatted data string directly to it:
Copy the Code code as follows:
var people =
{"Programmers": [
{"FirstName": "Brett", "LastName": "McLaughlin", "email": "Brett@newInstance.com"},
{"FirstName": "Jason", "LastName": "Hunter", "email": "Jason@servlets.com"},
{"FirstName": "Elliotte", "LastName": "Harold", "email": "Elharo@macfaq.com"}
],
"Authors": [
{"FirstName": "Isaac", "LastName": "Asimov", "Genre": "Science Fiction"},
{"FirstName": "Tad", "LastName": "Williams", "Genre": "Fantasy"},
{"FirstName": "Frank", "LastName": "Peretti", "Genre": "Christian Fiction"}
],
"Musicians": [
{"FirstName": "Eric", "LastName": "Clapton", "instrument": "Guitar"},
{"FirstName": "Sergei", "LastName": "Rachmaninoff", "Instrument": "Piano"}
]
}
This is very simple; now people contains the JSON-formatted data you saw earlier. However, this is not enough, because the way data is accessed doesn't seem to be obvious.
accessing data
Although it doesn't seem obvious, the long string above is really just an array, and after you put the array into a JavaScript variable, it's easy to access. In fact, you simply represent the array element with a dot notation. So, to access the last name of the first entry in the programmers list, just use the following code in JavaScript:
People.programmers[0].lastname;
Note that the array index is zero-based. So, this line of code first accesses the data in the people variable, then moves to the entry called programmers, then moves to the first record ([0]), and finally accesses the value of the LastName key. The result is a string value of "McLaughlin".
Here are a few examples of using the same variable.
Copy the Code code as follows:
People.authors[1].genre//Value is "fantasy"
People.musicians[3].lastname//Undefined. This refers to the fourth entry,
And there isn ' t one
People.programmers. [2].firstname//Value is ' Elliotte '
With this syntax, you can work with any JSON-formatted data without the need for any additional JavaScript toolkits or APIs.
modifying JSON data
Just as you can access data with dots and parentheses, you can easily modify the data in the same way:
People.musicians[1].lastname = "Rachmaninov";
After you convert a string to a JavaScript object, you can modify the data in the variable like this.
Convert back to String
Of course, if the object cannot be easily converted back to the text format mentioned in this article, then all data modifications are not of much value. This conversion is also simple in JavaScript:
String Newjsontext = people.tojsonstring ();
It's all right! Now you get a text string that can be used anywhere, for example, you can use it as a request string in an Ajax application.
More importantly, you can convert any JavaScript object to JSON text. You can not only handle variables that were originally assigned with a JSON string. In order to convert an object named MyObject, you only need to perform the same form of command:
String Myobjectinjson = myobject.tojsonstring ();
This is the biggest difference between JSON and other data formats discussed in this series. If you use JSON, just call a simple function, you can get the formatted data, you can use it directly. For other data formats, you need to convert between the original data and the formatted data. Even if you use an API such as the Document Object Model (which provides a function to convert your data structure to text), you need to learn the API and use the object of the API instead of using native JavaScript objects and syntax.
The final conclusion is that JSON is almost certainly a good choice if you are dealing with a large number of JavaScript objects, so you can easily convert the data into a format that can be sent to the server-side program in the request.
The application of JSON in PHP
The internet today, Ajax is no longer a strange word. Speaking of Ajax, it's possible to immediately think of XML emerging from RSS. XML parsing, I am afraid, is not a problem, especially PHP5, the emergence of a large number of XML parsers, such as the most lightweight simplexml. However, for Ajax, the parsing of XML is more inclined to the support of the foreground JavaScript. I think all the people who parse the XML will have a big head because of the tree and the node. Admittedly, XML is a very good way to store data, but its flexibility has caused the difficulty of its parsing. Of course, the difficulty referred to here is relative to the protagonist--json of this article.
What is JSON? I will not repeat the concept. In layman's words, it is a storage format for data, just like a string after PHP serialization. It is a data description. For example, when we serialize an array and store it, we can easily deserialize the post-serialization application. The same is true of JSON, except that he builds the interactive bridge between client-side JavaScript and server PHP. We use PHP to generate the JSON string, and then pass the string to the foreground javascript,javascirpt can easily be anti-JSON and then apply. Speaking of popular point, it really looks like an array.
Anyway, how to use JSON. PHP5.2 starts with the JSON support built in. Of course, if it is lower than this version, then there are many implementations of the PHP version on the market, the next use is OK. Now the main is to talk about PHP built-in support for JSON. Very simple, two functions: Json_encode and Json_decode (much like serialization). One encoding, one decoding. First look at the use of encoding:
Copy CodeThe code is as follows:
$arr = Array (
' Name ' = ' Home of the script ',
' Nick ' = ' Deep Space ',
' Contact ' = = Array (
' Email ' = ' shenkong at qq dot com ',
' website ' = ' http://www.jb51.net ',
)
);
$json _string = Json_encode ($arr);
echo $json _string;
?>
It's very simple to put an array json. It should be pointed out that in the non-UTF-8 encoding, the Chinese characters will not be encode, the result will be null, so if you use gb2312 to write PHP code, then you need to include Chinese content using Iconv or MB to UTF-8 and then Json_encode, The above output results are as follows:
{"Name": "/u9648/u6bc5/u946b", "Nick": "/u6df1/u7a7a", "contact": {"e-mail": "Shenkong at qq dot com", "website": "http:/// /www.jb51.net "}}
I've said it's like serialization, and you don't believe it. After encoding to decode, PHP provides the corresponding function Json_decode,json_decode execution, you will get an object, operation as follows:
Copy CodeThe code is as follows:
$arr = Array (
' Name ' = ' Home of the script ',
' Nick ' = ' Deep Space ',
' Contact ' = = Array (
' Email ' = ' shenkong at qq dot com ',
' website ' = ' http://www.jb51.net ',
)
);
$json _string = Json_encode ($arr);
$obj = Json_decode ($json _string);
Print_r ($obj);
?>
Access properties within an object will it? $obj->name, this, of course, can also be transferred to the array, convenient to call:
Copy CodeThe code is as follows:
$json _string = Json_encode ($arr);
$obj = Json_decode ($json _string);
$arr = (array) $obj;
Print_r ($arr);
The use of PHP is not particularly large, in addition to cache generation, the feeling is not as good as the direct storage array, but when you interact with the foreground, it is out of the role of it, below to see how I used JavaScript to use this character:
Copy CodeThe code is as follows:
Above, directly assign this string to a variable, it becomes a JavaScript array (professional terminology should not be called an array, but because of the habit of PHP, I have been called array good, easy to understand). In this way, you can easily traverse arr or do whatever you want. It doesn't seem to mention Ajax in this case? Yes, Lenovo, if the responsetext returned by the server replaces XML with a JSON string, is it convenient for the foreground JavaScript to be processed? That's how Dogskin plaster is used.
Actually written here, in addition to the data storage format is not the same, JSON and XML is not much different, oh, but I said the next point. Although it does not have much to do with XML, it is possible to describe a wider range of applications for JSON, that is, cross-domain data invocation. Because of security issues, Ajax does not support cross-domain calls, so to invoke different domain names under the data, very troublesome Oh, although there is a solution (stone in his lecture mentioned the agent ah what although not understand but know can solve). I wrote two files that were enough to show cross-domain calls.
Keynote file index.html
Copy CodeThe code is as follows:
Transferred Files profile.php
Copy CodeThe code is as follows:
$arr = Array (
' Name ' = ' Home of the script ',
' Nick ' = ' Deep Space ',
' Contact ' = = Array (
' Email ' = ' shenkong at qq dot com ',
' website ' = ' http://www.jb51.net ',
)
);
$json _string = Json_encode ($arr);
echo "GetProfile ($json _string)";
?>
Obviously, when Index.html calls Profile.php, the JSON string is generated and passed in as a parameter to the GetProfile, and then the nickname is inserted into the Div, so that the cross-domain data interaction is complete and is not particularly straightforward. Since JSON is so easy to use and useful, what are you waiting for? ^_^
JSON on the server side
Send JSON to the server
It is not difficult to send JSON to a server, but it is critical and there are important choices to make. However, once you decide to use JSON, the choices you make are simple and limited, so there are few things you need to consider and focus on. It is important to be able to send the JSON string to the server, and it is best to do it as quickly and as easily as possible.
Send JSON with name/value pairs via GET
The simplest way to send JSON data to the server is to convert it to text and then send it as a value of a name/value pair. It is important to note that JSON-formatted data is a fairly long object and may look like Listing 1:
Listing 1. Simple JavaScript objects in JSON format
Copy CodeThe code is as follows:
var people = {"Programmers": [{"FirstName": "Brett", "LastName": "McLaughlin",
"Email": "brett@newInstance.com"}, {"FirstName": "Jason", "LastName": "Hunter",
"Email": "jason@servlets.com"}, {"FirstName": "Elliotte", "LastName": "Harold",
"Email": "elharo@macfaq.com"}], "authors": [{"FirstName": "ISAAC",
"LastName": "Asimov", "Genre": "Science Fiction"}, {"FirstName": "Tad",
"LastName": "Williams", "Genre": "Fantasy"}, {"FirstName": "Frank",
"LastName": "Peretti", "Genre": "Christian Fiction"}], "Musicians": [
{"FirstName": "Eric", "LastName": "Clapton", "instrument": "Guitar"},
{"FirstName": "Sergei", "LastName": "Rachmaninoff", "Instrument": "Piano"}] }
If you want to send it to the server side as a name/value pair, it should look like this:
Copy CodeThe code is as follows:
var url = "organizepeople.php?people=" + people.tojsonstring ();
Xmlhttp.open ("GET", url, True);
Xmlhttp.onreadystatechange = Updatepage;
Xmlhttp.send (NULL);
This looks good, but there is a problem: there are spaces and various characters in the JSON data, and the Web browser tends to try to continue compiling it. To make sure that these characters do not cause confusion on the server (or in the process of sending data to the server), you need to add the following in the JavaScript Escape () function:
Copy CodeThe code is as follows:
var url = "organizepeople.php?people=" + Escape (people.tojsonstring ());
Request.open ("GET", url, True);
Request.onreadystatechange = Updatepage;
Request.send (NULL);
The function can handle spaces, slashes, and any other content that might affect the browser and convert them to Web-usable characters (for example, spaces are converted to%20, and the browser does not treat them as whitespace, but instead makes changes and passes them directly to the server). After that, the server will (usually automatically) convert them back to their original "face" after they are transmitted.
There are two drawbacks to this approach:
When sending large chunks of data using a GET request, there is a length limit on the URL string. Although this limitation is broad, the length of the object's JSON string representation may be more than you might think, especially when using extremely complex objects.
When all data is sent across the network in plain text, the security of sending data is beyond your processing power.
In short, these are the two limitations of a GET request, not just two things that are related to JSON data. When you want to send more content than your user name and last name, such as the choices in your form, you may need to be more careful. To work with any confidential or extremely long content, you can use a POST request.
Send JSON data with a POST request
When deciding to send JSON data to the server using a POST request, there is no need to make a lot of changes to the code, as follows:
Copy the Code code as follows:
var url = "organizepeople.php?timestamp=" + New Date (). GetTime ();
Request.open ("POST", url, True);
Request.onreadystatechange = Updatepage;
Request.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
Request.send (People.tojsonstring ());
Most of the code that you've seen in "Mastering Ajax, part 3rd: Advanced requests and responses in Ajax" should be familiar, and the 3rd focuses on how to send a POST request. The request is opened with POST instead of get, and the Content-type header is set to let the server know what data it can get. In this case, application/x-www-form-urlencoded, it lets the server know that the text is being sent, just as it would get from a regular HTML form.
Another simple hint is that the time is appended to the end of the URL. This ensures that the request will not be cached the first time it is sent, but will be recreated and re-sent after each invocation of the method, and this URL will be slightly different due to the timestamp. This technique is often used to ensure that the POST of the script actually generates a new request each time and that the WEB server does not attempt to cache the response from the server.
JSON is just text
Whether you use GET or POST, the key is that JSON is just text. Because no special coding is required and each server-side script can handle text data, it is easy to take advantage of the JSON and apply it to the server. If JSON is a binary format or some weird text encoding, the situation is not so simple; fortunately JSON is just regular text data (as can be seen in the POST and Content-type headers, as the script can receive from the form submission). So you don't have to worry about sending data to the server.
Interpreting JSON on the server
Once you have written client-side JavaScript code, allowed users to interact with Web Forms and Web pages, and collected the information needed to send to a server-side program for processing, the server becomes an application (if you invoke a server-side program that is used asynchronously, it is probably what we think of as the so-called " Ajax application "). At this point, the choices you make on the client (such as using JavaScript objects and then converting them to JSON strings) must match the server-side selection, such as which API is used to decode the JSON data.
Two steps to working with JSON
Regardless of the language used on the server side, processing the JSON on the server side basically requires two steps.
Find the appropriate JSON Parser/Toolbox/helper API for the language in which the server-side program is written.
Use the JSON parser/Toolbox/helper API to get the request data from the client and turn the data into something that the script can understand.
That's pretty much what we should know at the moment. Next, we describe each step in more detail.
Finding the JSON Parser
The best resource for finding a JSON parser or toolbox is the JSON site (see Resources for links). Here, in addition to knowing all aspects of the format itself, you can find a variety of links to JSON tools and parsers, from ASP to Erlang, to Pike, to Ruby. You only need to download the appropriate toolbox for the language you're scripting. To enable server-side scripts and programs to use this toolbox, you can select, extend, or install it as appropriate (if you use C #, PHP, or Lisp on the server side, it is more variable).
For example, if you are using PHP, you can simply upgrade it to PHP 5.2 and use it to complete the operation; the latest version of PHP includes the JSON extension by default. In fact, that's also the best way to work with JSON when using PHP. If you're using the Org.json package on Java servlet,json.org, it's obviously a good choice. In this case, you can download json.zip from the JSON Web site and add the source files contained therein to the project build directory. After compiling these files, everything is ready. You can also use the same steps for other languages that are supported, depending on how proficient you are with the language, preferably in a language that you are familiar with.
Using the JSON parser
Once you have the resources available to the program, the rest is to find the appropriate method to make the call. For example, suppose that PHP is using the json-php template:
Copy the Code code as follows:
This is just a code fragment from a larger PHP server-side script
Require_once (' json.php ');
$json = new Services_json ();
Accept POST data and decode it
$value = $json->decode ($GLOBALS [' http_raw_post_data ']);
Now work with value as raw PHP
With this template, you can convert any of the obtained data (anything in an array-formatted, multi-line, single-valued, or JSON data structure) into the native PHP format, placed in $value variable.
If the Org.json package is used in a servlet, the following code is used:
Copy CodeThe code is as follows:
public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
StringBuffer JB = new StringBuffer ();
String line = null;
try {
BufferedReader reader = Request.getreader ();
while (line = Reader.readline ()) = null)
Jb.append (line);
} catch (Exception e) {//report an error}
try {
Jsonobject jsonobject = new Jsonobject (jb.tostring ());
} catch (ParseException e) {
Crash and Burn
throw new IOException ("Error parsing JSON request string");
}
Work with the data using methods-like ...
int someint = Jsonobject.getint ("Intparamname");
String somestring = jsonobject.getstring ("Stringparamname");
Jsonobject nestedobj = Jsonobject.getjsonobject ("Nestedobjname");
Jsonarray arr = Jsonobject.getjsonarray ("Arrayparamname");
etc...
}
http://www.bkjia.com/PHPjc/621715.html www.bkjia.com true http://www.bkjia.com/PHPjc/621715.html techarticle The JSON Foundation simply says that JSON can convert a set of data represented in a JavaScript object into a string, which can then be easily passed between functions, or asynchronously ...