JSON Basics
Simply put, JSON converts a set of data represented in a JavaScript object into a string, which can then be easily passed between functions, or from a web client to a server in an asynchronous application terminal program. This string looks a little weird (you'll see a few examples later), but JavaScript interprets it easily, and JSON can represent more complex structures than name/value pairs. For example, arrays and complex objects can be represented rather than just simple lists of keys and values.
Simple JSON example
In its simplest form, a name/value pair can be represented in JSON like this:
This example is very basic and actually takes up more space than the equivalent plain text name/value pair:
However, JSON comes into its own when you string multiple name/value pairs together. First, you can create a record containing multiple name/value pairs, such as:
Syntactically, this isn't a huge 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; the curly braces make the values somehow related.
Array of values
JSON improves readability and reduces complexity when you need to represent a set of values. For example, suppose you want to represent a list of people's names. In XML, many start and end tags are required; if you use typical name/value pairs (like the ones you saw in previous articles in this series), a proprietary data format must be created , or change the key name to the form person1-firstName.
If using JSON, just group multiple records together with curly braces:
This is not difficult to understand. In this example, there is only one variable called people, and the value is an array of three entries, each entry being a record for a person containing a first name, last name, and email address. The above example demonstrates how to use parentheses to combine records into a single value. Of course, multiple values (each containing multiple records) can be expressed using the same syntax:
The most noteworthy thing 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 different main entries (programmers, authors, and musicians). JSON is fully dynamic, allowing the way data is represented to change in the middle of the JSON structure.
There are no predefined constraints that need to be adhered to when working with JSON-formatted data. Therefore, within the same data structure, the way the data is represented can be changed, and the same thing can even be represented in different ways.
Using JSON in JavaScript
Once you master the JSON format, using it in JavaScript is simple. JSON is a native JavaScript format, which means that processing JSON data in JavaScript does not require any special API or toolkit.
Assign JSON data to variables
For example, you can create a new JavaScript variable and assign a JSON-formatted data string directly to it:
This is very simple; now people contains the data in the JSON format we saw earlier. However, this is not enough as the way to access the data does not seem obvious yet.
Access data
Although it may not seem obvious, the long string above is actually just an array; you can easily access this array by placing it in a JavaScript variable. In fact, just use dot notation to represent array elements. So, to access the last name of the first entry in the programmers list, just use code like this in JavaScript:
Note that array indexing 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 the string value "McLaughlin".
Here are a few examples using the same variable.
With such a syntax, any JSON formatted data can be processed without using any additional JavaScript toolkit or API.
Modify JSON data
Just as data can be accessed using periods and brackets, data can be easily modified in the same way:
After converting the string to a JavaScript object, you can modify the data in the variable like this.
Convert back to string
Of course, all data modifications are of little value if you can't easily convert the object back to the text format mentioned in this article. This conversion is also simple in JavaScript:
That’s it! You now have a text string that you can use anywhere, for example, as a request string in an Ajax application. www.2cto.com
What's more, any JavaScript object can be converted to JSON text. It is not only possible to handle variables originally assigned with JSON strings. To convert an object named myObject, just execute a command of the same form:
This is the biggest difference between JSON and the other data formats discussed in this series. If you use JSON, you only need to call a simple function to get the formatted data, which is ready to use. For other data formats, conversion between raw and formatted data is required. Even when using an API like the Document Object Model (which provides functions to convert your own data structures to text), you need to learn the API and use the API's objects instead of using native JavaScript objects and syntax.
The bottom line is that if you're dealing with a large number of JavaScript objects, JSON is almost certainly a good choice so that you can easily convert the data into a format that can be sent to the server-side program in the request.
Application of JSON in PHP
In today's Internet, AJAX is no longer an unfamiliar word. Speaking of AJAX, XML that emerged due to RSS may immediately come to mind. XML parsing is probably no longer a problem, especially with PHP5 and the emergence of a large number of XML parsers, such as the most lightweight SimpleXML. However, for AJAX, XML parsing is more inclined to the support of front-end Javascript. I think everyone who has parsed XML will be confused by trees and nodes. It is undeniable that XML is a very good data storage method, but its flexibility makes it difficult to parse. Of course, the difficulty referred to here is relative to the protagonist of this article - JSON.
What is JSON? I won't repeat the concept. In layman's terms, it is a data storage format, just like a PHP serialized string. It is a data description. For example, if we serialize an array and store it, it can be easily deserialized and applied. The same is true for JSON, except that it builds an interactive bridge between client-side Javascript and server-side PHP. We use PHP to generate the JSON string, and then pass this string to the front-end Javascript. Javascirpt can easily convert it into JSON and then apply it. To put it in layman's terms, it really looks like an array.
Closer to home, how to use JSON. PHP5.2 has built-in support for JSON. Of course, if it is lower than this version, there are many PHP version implementations on the market, just use whichever one you want. Now we mainly talk about the JSON built-in support of PHP. Very simple, two functions: json_encode and json_decode (very similar to serialization). One for encoding and one for decoding. Let’s take a look at the use of encoding first:
$arr = array(
'name' => 'Linux',
'nick' => 'php',
'contact' => array(
'email' => 'email',
'website' => 'http://blog.csdn.net/21aspnet,
)
);
$json_string = json_encode($arr);
echo $json_string;
?>
It's very simple to JSON an array. It should be pointed out that under non-UTF-8 encoding, Chinese characters cannot be encoded, and the result will be null. Therefore, if you use gb2312 to write PHP code, you need to use iconv or mb to convert the content containing Chinese to UTF-8 and then json_encode, I have said that it is very similar to serialization, but you still don’t believe it. After encoding, it is necessary to decode. PHP provides the corresponding function json_decode. After json_decode is executed, an object will be obtained. The operation is as follows:
$arr = array(
'name' => 'Linux',
'nick' => 'php',
'contact' => array(
'email' => 'email',
'website' => 'http://blog.csdn.net/21aspnet,
)
);
$json_string = json_encode($arr);
$obj = json_decode($json_string);
print_r($obj);
?>
Is it possible to access the properties within the object? $obj->name, like this, of course, you can also convert it to an array for easy calling:
$json_string = json_encode($arr);
$obj = json_decode($json_string);
$arr = (array) $obj;
print_r($arr);
PHP is not very useful for moving around. In addition to cache generation, it feels like it is better to store the array directly. However, its role comes out when you interact with the front desk. Let's see how I use Javascript to use this. segment characters.
In the above, directly assign this string to a variable, and it becomes a Javascript array (the professional terminology should not be called an array, but due to PHP's habits, I will always call it an array for easier understanding). In this way, you can easily traverse arr or do whatever you want. I haven’t mentioned AJAX yet, right? Yes, think about it, if the responseText returned by the server uses a JSON string instead of XML, wouldn't it be very convenient for the front-end Javascript to process it? This is how dog skin plaster is used.
In fact, as I write this, except for the different data storage formats, there is not much difference between JSON and XML, but there is one point I will mention below. Although it has little to do with XML, it can illustrate the wider application of JSON, that is, cross-domain data calls. Due to security issues, AJAX does not support cross-domain calls. It is very troublesome to call data under different domain names. Although there are solutions (Stone mentioned proxies in his lecture, I don’t understand it but I know it) can be solved). I wrote two files, which are enough to demonstrate cross-domain calls.
Main file index.html