Applications of JSON and JSON in PHP

Source: Internet
Author: User
Tags php server
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, alternatively, the string is transmitted from the Web client to the server in an asynchronous application. JSON

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, alternatively, the string is transmitted from the Web client to the server in an asynchronous application. 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": "brett@newInstance.com" }

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 a typical name/value pair is used (like the name/value pair seen in the previous articles in this series ), 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": "brett@newInstance.com" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }
]}

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

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": "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; 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 code in JavaScript:

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 = "Rachmaninov";

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.
To put it bluntly, 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. Let's take a look at the encoding usage:


$ Arr = array (
'Name' => 'Chen yixin ',
'Nick '=> 'deep ary ',
'Contact '=> array (
'Email '=> 'shenkong at qq dot com ',
'Website' => 'http: // www.chenyixin.com ',
)
);
$ 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: \/www.chenyixin.com "}}
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:

$ Arr = array (
'Name' => 'Chen yixin ',
'Nick '=> 'deep ary ',
'Contact '=> array (
'Email '=> 'shenkong at qq dot com ',
'Website' => 'http: // www.chenyixin.com ',
)
);
$ 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:

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.