About JSON and JSON application techniques in PHP _php tips

Source: Internet
Author: User
Tags html form object model php server php template serialization javascript array stringbuffer

JSON Basics

Simply put, JSON converts a set of data represented in a JavaScript object to a string, which can then be easily passed between functions, or pass a string from a WEB client to a server-side program in an asynchronous application. This string looks a little odd (see some 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 with 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 is not a great advantage compared to name/value pairs, but in this case JSON is easier to use and more readable. For example, it is clear that the above three values are part of the same record; curly braces make these values a bit of a connection.

Array of values

When you need to represent a set of values, JSON not only improves readability, but it 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 pairs that you see in previous articles in this series), you must either create a proprietary data format or modify the key name to form Person1-firstname.

If you use JSON, you only need to group together multiple records with curly braces:

Copy Code code 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 record of one person, including first, last name, and e-mail address. The preceding example shows how to combine records into a single value in parentheses. Of course, you can use the same syntax to represent multiple values (each value contains multiple records):
Copy Code code 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. It should also be noted, however, that the actual name/value pairs in the record can be different between the main entries (programmers, authors, and musicians). JSON is completely dynamic, allowing you to change 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 that you represent the data, and you can even represent the same thing in different ways.

Using JSON in JavaScript

Once you have the JSON format, it's easy to use it in JavaScript. JSON is the native format of JavaScript, which means that processing 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 it directly to the JSON-formatted data string:

Copy 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 that you saw earlier. But that's not enough, because the way the data is accessed doesn't seem obvious.

accessing data

Although it doesn't look obvious, the long string above is actually just an array, and after you put the array in a JavaScript variable, you can easily access it. In fact, you just use dot notation to represent an array element. 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, moves to the entry called programmers, moves to the first record ([0]), and finally accesses the value of the LastName key. The result is the string value "McLaughlin".

Here are several examples of using the same variable.

Copy Code code as follows:

People.authors[1].genre//Value is "fantasy"
People.musicians[3].lastname//Undefined. This is 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 using 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 you can't easily convert an object back to the text format mentioned in this article, all data modifications are not of much value. This conversion is also simple in JavaScript:

String Newjsontext = people.tojsonstring ();

That'll do it! You now get a text string that you can use anywhere, for example, as a request string in an Ajax application.

More importantly, you can convert any JavaScript object to JSON text. It is not possible to handle only variables that were previously 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, simply 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 raw data and the formatted data. Even if you use an API such as 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, rather than 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 that you can easily convert the data into a format that can be sent to server-side programs in the request.

The application of JSON in PHP

The internet today, Ajax is not a strange word. Speaking of Ajax, you may immediately recall the XML that arose as a result of RSS. XML parsing, I am afraid, is no longer a problem, especially PHP5, the emergence of a large number of XML parsers, such as the most lightweight simplexml. But for Ajax, XML parsing is more likely to support the foreground JavaScript. I think all the people who have parsed the XML will have a big head because of the tree and the nodes. Admittedly, XML is a very good way to store data, but its flexibility precisely causes the difficulty of its parsing. Of course, the difficulty referred to here is relative to the protagonist--json in this article.
What is JSON? I will not repeat the concept. In layman's parlance, it is a storage format for data, just like a string after a PHP serialization. It is a data description. For example, after we have serialized an array and stored it, we can easily deserialize it and then apply it. The same is true of JSON, except that he builds an interactive bridge between client JavaScript and server PHP. We use PHP to generate the JSON string, and then pass this string to the foreground javascript,javascirpt can easily reverse JSON and then apply it. Speaking of popular point, it really looks like an array.
Anyway, how to use JSON. PHP5.2 began with the built-in JSON support. Of course, if lower than this version, then there are many PHP version of the implementation, just the next use on the OK. Now the main is to talk about PHP built-in support for JSON. Very simple, two functions: Json_encode and Json_decode (like serialization). One encoding, one decoding. First look at the use of the code:

Copy Code code as follows:

<?php
$arr = Array (
' Name ' => ' cloud-dwelling community ',
' 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 have an array of JSON. It should be pointed out that, in the UTF-8 encoding, the Chinese characters will not be encode, the result will come out null value, so if you use gb2312 to write PHP code, then you need to use the content of English to iconv or MB to UTF-8 and then Json_encode, The results of the above output are as follows:
{"Name": "/u9648/u6bc5/u946b", "Nick": "/u6df1/u7a7a", "Contacts": {"email": "Shenkong at qq dot com", "website": "http:/// /www.jb51.net "}}
I 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, will get an object, the operation is as follows:
Copy Code code as follows:

<?php
$arr = Array (
' Name ' => ' cloud-dwelling community ',
' 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 to properties within an object, right? $obj->name, this way, of course, you can also turn it to an array for easy invocation:
Copy Code code 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, it is not as good as direct storage array, but when you interact with the foreground, its role is out slightly, below see how I used JavaScript to use this paragraph of characters:
Copy Code code as follows:

<script type= "Text/javascript" >
var arr = {"name": "/u9648/u6bc5/u946b", "Nick": "/u6df1/u7a7a", "Contacts": {"email": "Shenkong at qq dot com", "website": " Http:////www.jb51.net "}};
Alert (Arr.name)
</script>

Above, directly assigning this string to a variable, it becomes a JavaScript array (the specialization term should not be called an array, but because of the habit of PHP, I have been called array well, easy to understand). This way, you can easily traverse the arr or do whatever you want to do. Writing here, it seems to have not mentioned Ajax Oh? Yes, and if the server-side returns responsetext with a JSON string instead of XML, is it convenient for the foreground JavaScript to handle it? That's how Dogskin plaster is used.
In fact, in addition to the data stored in the format is not the same, JSON and XML is not much different from Oh, but below I say a little. Although it has little to do with XML, it is possible to illustrate the broader application of JSON, that is, cross-domain data invocation. Because of security issues, Ajax does not support Cross-domain calls, so to invoke data under different domain names, it is troublesome, although there is a solution (stone in his lectures on the agent ah what I don't understand but know can solve). I wrote two files, enough to show the Cross-domain call.
Keynote file index.html
Copy Code code as follows:

<script type= "Text/javascript" >
function GetProfile (str) {
var arr = str;
document.getElementById (' Nick '). InnerHTML = Arr.nick;
}
</script>
<body><div id= "Nick" ></div></body>
<script type= "Text/javascript" src= "http://www.openphp.cn/demo/profile.php" ></script>

Profile.php of the document being transferred
Copy Code code as follows:

<?php
$arr = Array (
' Name ' => ' cloud-dwelling community ',
' 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 as a parameter to the GetProfile, and then the nickname is inserted into the Div, so that a cross-domain data interaction is done, and it is not particularly straightforward. Now that JSON is so simple and easy to use, what are you waiting for? ^_^

Server-Side JSON

Send JSON to Server

Sending JSON to a server is not difficult, but it is critical, and there are some important choices to make. However, once you decide to use JSON, these choices are simple and limited in number, so you need to consider and focus on a few things. 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 simple as possible.

Send JSON with name/value pairs via get

The easiest way to send JSON data to a server is to convert it to text and then send it as the value of the name/value pair. It is important to note that the JSON-formatted data is a fairly long object and may look like the one shown in Listing 1:

Listing 1. Simple JavaScript object in JSON format

Copy 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"}] }

If you want to send it to the server side as a name/value pair, you should do the following:
Copy Code code 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's a problem: there are spaces and various characters in the JSON data, and Web browsers tend to try to compile them. To ensure 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 Code code 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-available characters (for example, spaces are converted to%20 and browsers do not treat them as spaces, but instead change them directly to the server). Later, the server (usually automatically) converts them back to their original "face" after they are transmitted.

The disadvantages of this approach are two:

When sending large chunks of data using a GET request, there is a length limit on the URL string. Although this restriction is broad, the length of the object's JSON string representation may be beyond your imagination, especially when using extremely complex objects.

When you send all of your data across the network in plain text, the security of sending data is more than you can handle.

In short, these are the two limitations of GET requests, not the simple two things that are related to JSON data. When you want to send more content than your username and last name, such as a selection in a form, you may need to pay more attention. To handle any confidential or extremely long content, you can use a POST request.

Sending JSON data with POST requests

When you decide to use a POST request to send JSON data to the server, you do not need to make a large number of changes to the code, as follows:

Copy 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 these code, you've seen in "Mastering Ajax, part 3rd: Advanced requests and responses in Ajax," should be familiar, and part 3rd 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 predict what data it will have. In this case, the application/x-www-form-urlencoded, which lets the server know that the text is now being sent, just as it did from the regular HTML form.

Another simple hint is the time 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 resend after each invocation of the method, which will be slightly different because of the timestamp. This technique is often used to ensure that the POST of the script will actually generate a new request each time and the WEB server will 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 process text data, it is easy to take advantage of JSON and apply it to the server. If JSON is binary format or some weird text encoding, the situation is not so simple; Fortunately, JSON is just regular text data (as you can see in the POST and Content-type headers, as the script can receive from the form submission), So you don't have to worry too much when sending data to the server.

Interpreting JSON on the server

Once you have finished writing client JavaScript code, by allowing users to interact with Web Forms and Web pages, and collect the information they need to send to server-side programs for processing, the server becomes an application (if the server-side program used asynchronously is invoked, it may be what we think is called " Ajax application ") in the protagonist. At this point, the choices you make at the client (such as using a JavaScript object and then converting it to a JSON string) 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 JSON on the server side basically requires two steps.

For the language in which the server-side program is written, find the appropriate JSON Parser/Toolbox/helper API.

Use the JSON parser/Toolbox/helper API to get request data from the client and transform the data into something that the script understands.


That's pretty much what you should know now. Next, we introduce each step in more detail.

Looking for the JSON parser

The best resource for the JSON parser or Toolbox is the JSON site (see Resources for a link). Here, in addition to understanding all aspects of the format itself, you can find various tools and parsers for JSON, from ASP to Erlang, to Pike, to Ruby. You simply download the appropriate toolbox for the language in which you are writing your scripts. In order for server-side scripts and programs to use this toolbox, you can select, extend, or install them as appropriate (if you are using 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 contains the JSON extension by default. In fact, that's the best way to process JSON when using PHP. If you're using a Org.json package on a Java servlet,json.org, it's definitely a good choice. In this case, you can download json.zip from the JSON Web site and add the source files it contains to the project build directory. After compiling these files, everything is ready. You can also use the same steps for other languages that you support, and the language you use depends on how well you are proficient in the language, preferably in the language you are familiar with.

Using the JSON parser

Once you have the resources available to your program, the rest is to find the right way to invoke it. For example, suppose you are using a json-php template for PHP:

Copy 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 all the data you get (array-formatted, multiline, single-value, or any content in the JSON data structure) into native PHP format and put it in $value variable.

If the Org.json package is used in the servlet, the following code is used:

Copy Code code 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 ...
}

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: info-contact@alibabacloud.com 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.