Applications of JSON and JSON in PHP

Source: Internet
Author: User
Tags php server xml parser javascript array

JSON Basics

Simply put, JSON can convert a set of data represented in a javascript object to a string, and then it can be easily passed between functions, or asynchronously applied.ProgramTransmits the string from the Web Client to the server-side program. This string looks a bit odd (several examples will be seen later), but javascript can easily explain it, and JSON can represent a more complex structure than name/value pairs. For example, it can represent arrays and complex objects, not just a simple list of keys and values.

Simple JSON example

In the simplest form, you can use the following JSON to represent name/value pairs:

{"Firstname": "Brett "}

This example is very basic and actually takes more space than the equivalent plain text name/Value Pair:

Firstname = Brett

However, when multiple name/value pairs are concatenated, JSON will reflect its value. First, you can createRecordFor example:

{"Firstname": "Brett", "lastname": "McLaughlin", "email": " "}

In terms of syntax, this is not a great advantage over name/value pairs, but JSON is easier to use and more readable in this case. For example, it explicitly indicates that the above three values are part of the same record; curly braces make these values have a certain relationship.

Array of Values

To represent a group of values, JSON not only improves readability, but also reduces complexity. For example, assume that you want to list a person's name. In XML, many start and end tags are required. If you use a typical name/value pair (like before this series)Article), You must create a proprietary data format, or change the key namePerson1-firstNameThis form.

If JSON is used, you only need to group multiple records with curly braces:

{"People ":[
{"Firstname": "Brett", "lastname": "McLaughlin", "email": " "},
{"Firstname": "Jason", "lastname": "Hunter", "email": " "},
{"Firstname": "elliotte", "lastname": "Harold", "email": " "}

This is not hard to understand. In this example, there is only onePeopleThe value is an array containing three entries. Each entry is a person's record, including the name, last name, and email address. The preceding example demonstrates how to use parentheses to combine records into a value. Of course, you can use the same syntax to represent multiple values (each value contains multiple records ):

 {"programmers": [
 {"firstname": "Brett", "lastname ": "McLaughlin", "email": "" },< br> {"firstname": "Jason", "lastname": "Hunter", "email ": "" },< br> {"firstname": "elliotte", "lastname": "Harold", "email": ""} 
 "Authors": [
 {"firstname": "Isaac", "lastname": "Asimov", "genre": "Science Fiction "}, 
 {"firstname": "tad", "lastname": "Williams", "genre": "Fantasy" },< br> {"firstname ": "Frank", "lastname": "Peretti", "genre": "Christian fiction"} 
 "musicians ": [
 {"firstname": "Eric", "lastname": "Clapton", "instrument": "Guitar" },< br> {"firstname ": "Sergei", "lastname": "Rachmaninoff", "instrument": "Piano" }< br>] 

It is worth noting that each value can contain multiple values. However, you should also note that the actual name/value pairs in the record can be different between different primary entries (programmers, authors, and musicians. JSON is completely dynamic and allows you to change the data representation mode in the middle of the JSON structure.

When processing data in JSON format, there are no predefined constraints to be observed. Therefore, in the same data structure, you can change the way data is represented, or even express the same thing in different ways.

Use JSON in Javascript

After mastering the JSON format, it is easy to use it in JavaScript. JSON is a javascript native format, which means that no special API or toolkit is required to process JSON data in JavaScript.

Assign JSON data to a variable

For example, you can create a new JavaScript variable and assign a value to the JSON-format data string:

 var people = 
 {"programmers": [
 {"firstname": "Brett ", "lastname": "McLaughlin", "email": "" },< br> {"firstname": "Jason", "lastname": "Hunter ", "email": "" },< br> {"firstname": "elliotte", "lastname": "Harold", "email ": ""} 
 "Authors": [
 {"firstname": "Isaac", "lastname": "Asimov ", "genre": "Science Fiction" },< br> {"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" }< br>] 

This is very simple; nowPeopleContains the preceding JSON data. However, this is not enough, because the data access method does not seem obvious.

Access Data

Although the above long string is actually an array, the array can be easily accessed after it is put into JavaScript variables. In fact, you only need to use the dot notation to represent array elements. Therefore, to access the first project name in the programmers list, you only need to use the following in javascript:Code:

People. Programmers [0]. lastname;

Note that the array index starts from scratch. Therefore, this line of code first accessesPeopleThe data in the variable.ProgrammersAnd then move to the first record ([0]); Finally, accessLastnameKey value. The result is the string value "McLaughlin ".

The following are examples of using the same variable.

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 process data in any JSON format without using any additional JavaScript toolkit or API.

Modify JSON data

Just as you can access data with periods and parentheses, you can easily modify the data in the same way:

People. Musicians [1]. lastname = "Your maninov ";

After converting a string to a JavaScript Object, you can modify the data in the variable as follows.

Convert back to string

Of course, if you cannot easily convert an object back to the text format mentioned in this article, all data modifications are of little value. In JavaScript, this conversion is also very simple:

String newjsontext = people. tojsonstring ();

That's all! Now you can obtain 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 canAnyThe JavaScript Object is converted to JSON text. It is not only applicable to variables that are originally assigned values using JSON strings. ToMyobjectTo convert objects, you only need to execute commands in the same form:

String myobjectinjson = myobject. tojsonstring ();

This is the biggest difference between JSON and other data formats discussed in this series. If JSON is used, you only need to call a simple function to obtain formatted data and use it directly. For other data formats, the conversion between the original data and the formatted data is required. Even if you use an API like Document Object Model (which provides a function to convert your data structure to text), you also need to learn this API and use the object of the API, instead of using native JavaScript objects and syntaxes.

The final conclusion is that if you want to process a large number of JavaScript objects, JSON is almost certainly a good choice, so that you can easily convert the data to a format that can be sent to the server-side program in the request.

Application of JSON in PHP

today, Ajax is no stranger to the Internet. When talking about Ajax, you may immediately think of XML that has emerged due to RSS. XML parsing is no longer a problem, especially PhP5. A large number of XML Parser emerged, such as simplexml, which is the most lightweight. However, for Ajax, XML parsing tends to support JavaScript at the front end. I think all the people who have parsed XML will be headers of trees and nodes. It is undeniable that XML is a good data storage method, but its flexibility has caused difficulties in parsing. Of course, the difficulty mentioned here is relative to JSON, the main character of this article.
what is JSON? I will not repeat the concept. In general, it is a data storage format, just like the serialized string in PHP. It is a data description. For example, if we store an array after serialization, we can easily apply it after deserialization. JSON is the same, but it builds a bridge between client JavaScript and server PHP. We use PHP to generate the JSON string, and then pass the string to the front-end Javascript. Then we can easily apply the javascirpt anti-JSON string. It is really like an array.
back to the truth, how to use JSON. Php5.2 has built-in support for JSON. Of course, if it is earlier than this version, there are many PHP versions available on the market, and it will be OK as soon as the next version is used. Now we mainly talk about the built-in JSON supported by PHP. Very simple: two functions: json_encode and json_decode (similar to serialization ). One encoding and one decoding. First, let's look at the encoding usage:

<? PHP
$ Arr = array (
'Name' => 'chen yixin ',
'Nick '=> 'deep ary ',
'Contact '=> array (
'Email '=> 'shenkong at QQ dot com ',
'Website' => 'HTTP: // ',
$ Json_string = json_encode ($ ARR );
Echo $ json_string;
Simply put an array in JSON format. It should be noted that, in non-UTF-8 encoding, Chinese characters will not be encode, the results will be null, So if you use gb2312 to write PHP code, then we need to use iconv or MB to convert the content containing Chinese characters into a UTF-8 and then perform json_encode. The above output result is as follows:

{"Name": "\ u9648 \ u6bc5 \ u946b", "Nick": "\ u6df1 \ u7a7a", "Contact": {"email ": "shenkong at QQ dot com", "website": "http: \/ "}}
I have said that it is similar to serialization. You still don't believe it. Decoding is required after encoding. php provides the corresponding function json_decode. After json_decode is executed, an object is obtained. The operation is as follows:

<? PHP
$ Arr = array (
'Name' => 'chen yixin ',
'Nick '=> 'deep ary ',
'Contact '=> array (
'Email '=> 'shenkong at QQ dot com ',
'Website' => 'HTTP: // ',
$ Json_string = json_encode ($ ARR );
$ OBJ = json_decode ($ json_string );
Print_r ($ OBJ );
Will access the attributes in the object? $ Obj-> name. Of course, you can also index the array to facilitate the call:

$ Json_string = json_encode ($ ARR );
$ OBJ = json_decode ($ json_string );
$ Arr = (array) $ OBJ;
Print_r ($ ARR );
PHP transfer and transfer are not very useful. In addition to cache generation, it feels better to store arrays directly. However, when you interact with the front-end, the function will come out, next let's take a look at how I use JavaScript to use this character:

<SCRIPT type = "text/JavaScript">
VaR arr = {"name": "\ u9648 \ u6bc5 \ u946b", "Nick": "\ u6df1 \ u7a7a", "Contact": {"email ": "shenkong at QQ dot com", "website": "http: \/ "}};
Alert (ARR. Name)
In the above, the string is directly assigned to a variable, and it becomes a JavaScript Array (specialized terms should not be called arrays, but due to the habits of PHP, I have been calling Arrays for ease of understanding ). In this way, you can easily traverse the ARR or do whatever you want. It seems that AJAX is not mentioned here? Yes. In retrospect, if the server returns responsetext with a JSON string instead of XML, will the front-end JavaScript processing be very convenient? Dog Skin plaster is used in this way.
As a matter of fact, apart from the different storage formats of data, there is no big difference between JSON and XML. Although it does not have much to do with XML, it can indicate a wider range of JSON applications, that is, cross-Origin data calls. Due to security issues, Ajax does not support cross-origin calls. Therefore, it is very troublesome to call data under different domain names, although there is a solution (stone mentioned proxy in his lecture. Although he doesn't understand it, he knows it can solve it ). I wrote two files to demonstrate cross-origin calls.
Access key file index.html
<SCRIPT type = "text/JavaScript">
Function getprofile (STR ){
VaR arr = STR;
Document. getelementbyid ('Nick '). innerhtml = arr. Nick;
<Body> <Div id = "Nick"> </div> </body>
<SCRIPT type = "text/JavaScript" src = ""> </SCRIPT>
Profile. php
<? PHP
$ Arr = array (
'Name' => 'chen yixin ',
'Nick '=> 'deep ary ',
'Contact '=> array (
'Email '=> 'shenkong at QQ dot com ',
'Website' => 'HTTP: // ',
$ Json_string = json_encode ($ ARR );
Echo "getprofile ($ json_string )";
Obviously, when index.html calls profile. php, The JSON string is generated and passed into getprofile as a parameter, and then the nickname is inserted into the Div. This completes a cross-Origin data interaction. Is it very simple. Since JSON is so easy to use and easy to use, what are you waiting? Pai_^

Server-side JSON

Send JSON to server

It is not difficult to send JSON to the server, but it is crucial and there are some important options to do. However, once you decide to use JSON, these options will be very simple and limited, so there are not many things 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 soon as possible and as simple as possible.

Use get to send JSON data with name/value pairs

The simplest way to send JSON data to the server is to convert it into text and then send it as the value of the name/value pair. It is important to note that the data in JSON format is a fairly long object and may appear as shown in Listing 1:

Listing 1. Simple JavaScript objects in JSON format

VaR people = {"programmers": [{"firstname": "Brett", "lastname": "McLaughlin ",
"Email": "" },{ "firstname": "Jason", "lastname": "Hunter ",
"Email": "" },{ "firstname": "elliotte", "lastname": "Harold ",
"Email": ""}], "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 a name/value pair to the server, it should be 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 JSON data, and Web browsers often have to try to compile it. To ensure that these characters do not cause confusion on the server (or when sending data to the server ),Escape ()Add the following in the function:

VaR url = "organizepeople. php? People = "+Escape (People. tojsonstring ());
Request. Open ("get", URL, true );
Request. onreadystatechange = updatepage;
Request. Send (null );

This function can process spaces, diagonal lines, and any other content that may affect the browser, and convert them into available web characters (for example, spaces are converted% 20The browser does not treat it as a space, but does not change it and directly transmits it to the server ). Then, the server will (usually automatically) convert them back to their original "face" after transmission ".

There are two disadvantages of this practice:

    • The URL string length is limited when a GET request is used to send large data blocks. Although this restriction is broad, the length of the object's JSON string representation may exceed your imagination, especially when using extremely complex objects.
    • When sending all data in plain text across networks, the security of data transmission exceeds your processing capability.

In short, the above are two restrictions on GET requests, not two simple things related to JSON data. When you want to send more content beyond the user name and surname, such as the selection in the form, you may need to pay more attention to the two. To process any confidential or extremely long content, you can use post requests.

Send JSON data using post requests

When you decide to use the POST request to send JSON data to the server, you do not need to make a lot of changes to the Code, as shown below:

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,Understanding Ajax, part 1: Advanced request and response in Ajax. I should be familiar with it. Part 1 focuses on how to send post requests. The request is opened using post instead of get, and the Content-Type header is set to let the server know what data it can get. In this caseApplication/X-WWW-form-urlencodedIt allows the server to know that the text is sent, just as it gets from the regular HTML form.

Another simple prompt is the append time at the end of the URL. This ensures that the request will not be cached after it is sent for the first time, but will be re-created and re-issued after each call of this method; the URL varies slightly depending on the timestamp. This technique is often used to ensure that a new request is generated every time a script post is sent, and the Web server does not try to cache responses from the server.

JSON is just text

Whether get or post is used, the key is that JSON is only text. Because no special encoding is required and each server-side script can process text data, JSON can be easily used and applied to the server. If JSON is in binary format or some weird text encoding, the situation is not that simple. Fortunately, JSON is only the regular text data (just as the data that the script can receive from form submission, as can be seen in the post segment and Content-Type headers), you do not have to worry too much when sending data to the server.

Explain JSON on the server

Once you write the client JavaScript code, allow users to interact with web forms and web pages, and collect the information required for processing sent to the server program, the server becomes the main character of an application (if an Asynchronous Server program is called, it may be a so-called "Ajax application. At this time, your selection on the client (for example, using a JavaScript Object and then converting it into a JSON string) must match the selection on the server side, for example, which API is used to decode JSON data.

Two steps for processing JSON

Regardless of the language used on the server, two steps are required to process JSON on the server.

    1. Find the corresponding JSON parser/toolbox/helper API for the language used to write the server-side program.
    2. Use the JSON parser/toolbox/helper API to retrieve request data from the client and convert the data into something that the script can understand.

The above is about what we should know. Next, we will introduce each step in detail.

Search for the JSON parser

The best resource for finding a JSON parser or toolbox is the JSON site (for links, see references ). In addition to understanding all aspects of the format itself, you can also find various JSON tools and Resolvers through various links, from ASP to Erlang, to Pike, and then to Ruby, everything. You only need to download the toolbox for the language used to write your own scripts. To enable server scripts and programs to use this toolkit, you can select, expand, or install it as needed (if the server uses C #, PHP, or lisp, 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 contains the JSON extension by default. In fact, it is also the best way to process JSON when using PHP. If Java Servlet is usedOrg. JSONPackage is obviously a good choice. In this case, you can download from the JSON web site and add the included source files to the Project Build directory. After these files are compiled, everything is ready. The same procedure can also be used for other Supported languages. The language you use depends on your proficiency in the language, and it is best to use the language you are familiar.

Use the JSON parser

Once the available resources of the program are obtained, the only thing left is to find the appropriate method for calling. For example, suppose PHP uses a JSON-PHP template:

// 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

This template can be used to convert all the obtained data (array format, multiline, single-value, or any content in the JSON Data Structure) to the native PHP format and place it in$ ValueVariable.

If you useOrg. JSONThe following code is used:

 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 = new jsonobject (JB. tostring (); 
}catch (parseexception e) {
 // crash and burn 
 throw new ioexception ("error parsing JSON request string "); 
}< br> 
 // 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... 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.