Explanation of json

Source: Internet
Author: User
Tags tojson

After studying the JSON array format for a long time, I would like to share with you that you have certainly gained a lot after reading this article. I hope this article will teach you more things. When learning the JSON array format.
Let's start the journey of this new concept. This topic of serialization may not have been paid much attention before. In fact, things actually originated from turning over the PHP manual that day and finding this serialized function, after that, I was bored and made another plug-in the JSON array format. At this time, I used serialization and found that it was indeed very convenient in some cases.

First, let's explain serialization: in simple words, serialization converts a variable into a word throttling process. The serialization method effectively solves the storage and transmission of objects. For example, I set up an object in JavaScript, I want to save this object to the database on the server. How can I perform this operation? In this case, the serialization of objects is often used.

• How to better encapsulate JSON objects for the JSONObject plug-in
• How to correctly add parameters using the JSONP request address
• Instructions on using Javascript Json objects ..
• Instructions for using JSON Complex Structures
• Description of the relationship between the JSON standard and JavaScript ..
In the serialization of JavaScript, we have to mention the JSON array format. JSON (JavaScript Object Notation) is a lightweight data exchange format. Easy for reading and writing, and easy for machine parsing and generation. It is based on JavaScript Programming Language and a subset of the JSON array format. JSON uses a completely language-independent text format, but it also uses a habit similar to the C language family (including C, C ++, C #, Java, JavaScript, Perl, Python, and so on ). These features make JSON an ideal data exchange language.

• How to better encapsulate JSON objects for the JSONObject plug-in
• How to correctly add parameters using the JSONP request address
• Instructions on using Javascript Json objects ..
• Instructions for using JSON Complex Structures
• Description of the relationship between the JSON standard and JavaScript ..
People usually compare JSON and JSON array formats. Both of them are a means of flattening objects (We will explain this "flattening" Later). XML is characterized by a rigorous structure, JSON is easy to read and analyze, because it can easily convert an object into a pipeline stream, for example, the following code:

1. {"type": "human", "name": "hanguofeng", "age": 22} is a JSON expression, which saves an object, how can we restore it to an object? It is very simple, as follows:

1. var animal_str = '{"type": "human", "name": "hanguofeng", "age": 22 }'; 2.var animal = eval ('+ animal_str +'); we use the evaluate function of JavaScript to calculate the JSON expression and return the value to obtain an object, here, I think you will surely feel the same as me and admire the creators of JSON format. I used to talk about serialization. I was "not careful" about the JSON array format and talked about it so much. Why? No. PHP serialization and JSON are very similar. a php serialization expression is as follows:
A: 3: {s: 4: "type"; s: 5: "human"; s: 4: "name"; s: 10: "hanguofeng"; s: 3: "age"; s: 2: "20 ";}

It seems that the structure is similar to JSON. In fact, this expression is serialized as follows:

$ Animal =
Array
(
"Type" => "human ",
"Name" => "hanguofeng ",
"Age" => "20"
);

Why

Serialization first emerged as a convenience of data transmission. As I mentioned at the beginning of this article, I have created an object in JavaScript, what should I do if I want to save this object to the database on the server? This is actually a question about how I submit an object to the server from the browser, in this transmission process, we know that we can only pass the pipeline stream. The pipeline stream is one-dimensional (flat), but many objects are multidimensional. If the object to be transmitted is a string, we can simply use it as the passed content. If the object to be passed is an array or another structure, we need to describe it using the transform stream, for example, on the phone, if I ask what your name is, you will tell me that your name is James and James, and I ask you, what is your appearance, you need to describe to me in text. The media for data transmission is often the same as that for this telephone line. We can only pass the gossip stream, but we describe the object process, it is actually a process of serialization.
In addition, serialization can also be used for persistent storage of objects, and you may have stored an object in a field of the database like me, now we can do this very simply, and you do not need to set this database field to a special format or varchar (of course, if the object is large, you may need to set it to text ).
How
PHP serialization syntax
Well, I think you have learned about What and Why. At the end of this section, we will talk about more theoretical content, that is, how to use PHP to serialize and deserialize data, how to serialize JavaScript objects (that is, convert them to JSON format), how to deserialize them, and finally how to establish the relationship between JSON and PHP serializing.
PHP provides two functions for serialization and deserialization. These two functions are serialize () and unserialize (), which are applicable to PHP4 and PHP5, the following are the explanations:
Serialize ()
(PHP 4, PHP 5, PECL axis2: 0.1.0-0.1.1)
Serialize-get a stored expression value
Description
String serialize (mixed $ value)
Obtain a stored expression value
This function is used to store or transmit PHP variable values and structures without any loss.
To convert serialized values back to PHP variables, you can use the unserialize () function.
Parameters
Value
The serialized expression. Serialize () processes all types except resource pointers. You can even serialize arrays containing elements pointing to itself. Your serialized arrays or objects that contain loops are stored, and other objects that point to them are lost.
When serializing an object, PHP tries to call its member function _ sleep () first (). This allows objects to perform final cleaning before being serialized. Similarly, when the unserialize () function is used to restore an object, the member function _ wakeup () is called ().
Return Value
Returns a string containing the object's byte stream expression that can be stored anywhere.
Unserialize ()
(PHP 4, PHP 5, PECL axis2: 0.1.0-0.1.1)
Unserialize-get a PHP variable value from a stored expression
Description
Mixed unserialize (string $ str)
Unserialize () gets a simple type of serialized variable and converts it back to the PHP variable value.
Parameters
Str
Serialized string
If the variable to be deserialized is an object, PHP automatically tries to execute the _ wakeup () member functions (if they exist ).
Unserialize_callback_func command: You can set the callback function to be executed during this process, if an undefined class should be instantiated during deserialization (to avoid obtaining an incomplete object "_ PHP_Incomplete_Class "). You can use php. ini, ini_set (), or. htaccess to define "unserialize_callback_func ". When an unspecified class is instantiated, it is called. To block this feature, you only need to set it to null.
Return Value
Returns the converted value, which may be a Boolean variable, a real number, a floating point number, a string, an array, or an object.
If the input string cannot be deserialized, FALSE is returned and a NOTICE error is thrown.
(Translated from the PHP manual)
PHP serialization instance
Serializing and deserializing Arrays
OK. Let's take a look at the example. First, create the sample1.php file. In this file, use the following statement to create a hash array:

Copy the content to the clipboard code:
<? Php
$ Animal =
Array
(
"Type" => "human ",
"Name" => "hanguofeng ",
"Age" => "20"
);
?>

To test the value of this array, you can use the print_r () function to output the array. The output result is as follows:

Copy the content to the clipboard code: Array
(
[Type] => human
[Name] => hanguofeng
[Age] => 20
)

Then we will serialize it. The serial code is as follows:

Copy the content to the clipboard code: <? Php
$ Animal =
Array
(
"Type" => "human ",
"Name" => "hanguofeng ",
"Age" => "20"
);
$ Animal_ser = serialize ($ animal );
Echo ($ animal_ser );
?>

Here we serialize the array $ animal, save the returned serialized string in the variable $ animal_ser, and output the following output:

Copy the content to the clipboard code: a: 3: {s: 4: "type"; s: 5: "human"; s: 4: "name"; s: 10: "hanguofeng"; s: 3: "age"; s: 2: "20 ";}

Let's simply parse this string:
A: 3 indicates that this is an array object (a). It has three built-in objects (3)
The content in braces is a list of comma-separated object expressions. Taking s: 4: "type" as an example, it represents a string (s) with a length of 4 bits (4 ), the value is "type", that is, the key of the first element of the hash array.
We will not repeat the subsequent sections. You can try serializing various objects and see how the serialized strings are constructed.
Next, let's take a look at the array's deserialization, which restores the serialized string we generated above to an array. The Code is as follows:

Copy the content to the clipboard code: <? Php
$ Animal_ser = 'a: 3: {s: 4: "type"; s: 5: "human"; s: 4: "name"; s: 10: "hanguofeng"; s: 3: "age"; s: 2: "20 ";}';
$ Animal = unserialize ($ animal_ser );
Print_r ($ animal );
?>

In the first row, assume that the value of $ animal_ser is the serialized string obtained above. In the second row, the string is restored to the starting array and assigned to $ animal, finally, the $ animal array is output. The output is the same as the original array at the beginning of this section, that is:

Copy the content to the clipboard code: Array
(
[Type] => human
[Name] => hanguofeng
[Age] => 20
)

In this way, the array is deserialized.
Extended knowledge-serialization and deserialization of custom objects
Serialization of arrays is a basic operation. However, in actual programming, we may often serialize other types of variables, such as serializing a custom object, here is A self-compiled Class A (saved in classa. inc ):

Copy the content to the clipboard code: <? Php
Class {
Var $ one = 1;
Function show_one (){
Echo $ this-> one;
}
}
?>

Create a class instance in the following code and serialize the instance:

Copy the content to the clipboard code: <? Php
Include ("classa. inc ");
$ A = new;
Echo (serialize ($ ));
?>

The output content is as follows:

Copy the content to the clipboard code: O: 1: "A": 1: {s: 3: "one"; I: 1 ;}

In general, this serialized string outputs the current state of the modified object, that is, the value of I is 1. Next we will analyze the details one by one.
O: 1: because the current variable is a custom Object, the character "O" indicates the Object.
The following "A" identifies the instance of the class of the variable, which is Class.
The name and value of each attribute of the instance are enclosed in braces.
Then we will deserialize it:

Copy the content to the clipboard code: <? Php
Include ("classa. inc ");
$ S = 'O: 1: "A": 1: {s: 3: "one"; I: 1 ;}';
$ A = unserialize ($ s );
$ A-> show_one ();
?>

In this case, "1" is output, that is, the show_one () method of Class A is called.
You can note that although the serialized strings of an instance do not contain Class methods, we can still call class methods after deserializing them, this feature is supported in PHP4 and later versions (of course, you need to include the class definition file classa. inc ).
Note: You can refer to the section "Language Reference-> Classes and Objects-> Serializing objects-objects in sessions" in the PHP manual.
Serialize to JSON in JavaScript-use json2.js
There is no built-in method for directly serializing objects in JavaScript. Of course you can write one by yourself, but I strongly recommend that you steal a little lazy and use ready-made components here, the official JSON website www.json.org provides a JSON serialized code base for JavaScript objects-json2.js, which you can obtain from here.
After obtaining the json2.js file, you can open the file, which contains a large amount of comments before the file. If your English is good enough, you can omit this section and refer to the comments in this file. As a programmer, you have read a large number of letters and want to see my Chinese characters and letters, then you can continue.
Simple translation of this comment:
See http://www.JSON.org/js.html
This file creates a global object JSON that contains two methods. The methods are as follows:

Copy the content to the clipboard code: JSON. stringify (value, whitelist)

Any JavaScript value of value, usually an object or Array
Whitelist is an optional array parameter used to determine how object values are serialized.
This method uses a JavaScript value to generate JSON text. During serialization, there are three possible options based on the optional parameter whitelist:
If an object has a toJSON method, this method is called and the return value of the toJSON method is serialized.
Otherwise, if the optional parameter whitelist is an array, the elements in the array will be used to select members when the object is serialized.
Otherwise, if the whitelist parameter is not used, all the members of the object will be serialized.
If the value does not have a JSON representation, such as undefined or function, it will not be serialized. In the object, such values are ignored, and null is replaced in the array.
JSON. stringify (undefined) returns undefined. The date will be serialized as the referenced ISO date.
Example:

Copy the content to the clipboard code: var text = JSON. stringify (['E', {pluribus: 'unum'}]);
// Text is '["e", {"pluribus": "unum"}]'
JSON. parse (text, filter)

This method parses a JSON text and generates a component or array, which may throw a SyntaxError exception.
The optional filter parameter is a function that can filter and convert results. It accepts each key and value, and its return value is used to replace the source value. If it returns the received value, the result will not be changed. If undefined is returned, the Member is deleted.
Example:

Copy the content to the clipboard code: // parse the text. If a key contains the string "date", the value is converted to a date.
MyData = JSON. parse (text, function (key, value ){
Return key. indexOf ('date')> = 0? New Date (value): value;
});

The above getting started tutorials have given you a basic understanding of how to use json2.js. I will not go into details about this file here, but there is a small tip. If you want to parse a JSON text, you can use the eval () function, which is a built-in function of JavaScript, for example, parsing in JSON. the JSON text generated in the stringify case can be used:

Copy the content to the clipboard code: var myE = eval ('["e", {"pluribus": "unum"}]');

To obtain the object myE.
Serialized as JSON in JavaScript-use prototype. js
If you like me and like to use open-source JavaScript frameworks in your own projects, you may not need to use the json2.js file. Here we use protype. js as an example, the file can be downloaded in the http://www.prototypejs.org, because this article is not about the JavaScript framework, here I suppose you have prototype. I have learned about using js.
Prototype. js provides the toJSON Method for Object objects. You can use the Object. toJSON () method to serialize objects. For example:

Copy the content to the clipboard code: var cat =
{
Name: "hellokitty ",
Height: "6 apples"
}
Alert (Object. toJSON (cat ));
// The displayed dialog box contains {"name": "hellokitty", "height": "6 apples "}

In addition, prototype. js also supports JSON, which is mainly used to parse JSON content in Ajax return requests. This is not relevant to our content for the moment, and we will not introduce it any more.
PHP and JSON
We have learned how PHP serializes objects and how to serialize objects into JSON in JavaScript. You may question why I put them together, because their syntax is not exactly the same, in PHP, JSON text can be deserialized, you can also serialize PHP objects into JSON rather than PHP-style text. These functions are mainly implemented by json_decode and json_encode. Note that these two functions are only supported in PHP 5> = 5.2.0, if you want to write a program running in the PHP4 environment, these two functions cannot be used.
Json_decode Function
Syntax
Mixed json_decode (string $ json [, bool $ assoc])
Get a JSON encoded text and convert it to a PHP variable
Parameters
Json
JSON-encoded text
Assoc
If it is TRUE, the returned value is a Union array.
Return Value
Returns an object, or if the optional assoc parameter is TRUE, a union array is returned.
Json_encode Function
Syntax
String json_encode (mixed $ value)
This function returns a JSON expression of the value.
Parameters
Value
The value to be encoded. It can be any type parameter except resource.
This function only works in UTF-8 encoding formats
Return Value
The encoded JSON text is returned when the request succeeds.
Json_decode function instance
The two examples below are based on one of our scenario assumptions, that is, we have a user registration module that works in an "Object-Oriented" way. In the json_decode function instance, in the previous step, we changed the user registration information into a class attribute and then passed it to the PHP file in the background (for convenience, Ajax is not needed here ). In the json_encode instance, we reference a js file in the html file. The address points to the PHP file and outputs The json-encoded user object in the PHP file (also for ease of use, we directly generate an object without receiving information from the database) and output it in html.
Now let's take a look at the front page json_encode.htm. This page imitates the usual registration page and has a form on it. When submitted, the JavaScript function is triggered to generate a user object, set the form content to the attributes of the user object, generate JSON text, and pass it to the json_encode.php file in POST mode. In the js_encode.php file, parse the JSON text into a PHP Object using the json_decode function and output it.
Now let's take a look at the json_encode.html file. The file code is as follows:

Copy the content to the clipboard code: <! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> json_decode </title>
<Script src = "json2.js" type = "text/javascript"> </script>
<Script type = "text/javascript">
Function JSON_test (o)
{
Var user = {
Name: document. getElementById ('txt _ name'). value,
Email: document. getElementById ('txt _ email '). value,
Password: document. getElementById ('txt _ name'). value
}
Var json_string = JSON. stringify (user );
Document. getElementById ('txt _ json'). value = json_string;
Alert ("Click OK to submit the form ");
O. submit ();
}
</Script>
</Head>
<Body>
<Form id = "form1" name = "form1" method = "post" action = "json_encode.php" onsubmit = "JSON_test (this)">
<Label for = "txt_name"> name </label>
<P>
<Input type = "text" name = "txt_name" id = "txt_name"/>
</P>
<Label for = "txt_email"> email address </label>
<P>
<Input type = "text" name = "txt_email" id = "txt_email"/>
</P>
<P>
<Label for = "txt_password"> password </label>
</P>
<P>
<Input type = "text" name = "txt_password" id = "txt_password"/>
</P>
<P>
<Input type = "text" name = "txt_json" id = "txt_json"/>
<Label for = "button"> </label>
<Input type = "submit" name = "button" id = "button" value = "JSON"/>
</P>
</Form>
</Body>
</Html>

When a form is submitted, the JavaScript function JSON_text () is triggered. This function first creates a JavaScript Object user and sets its name, email, and password attributes to the values of the corresponding form, respectively, then use the json of the json2.js file. the stringify method converts it to the JSON text json_string, and finally sets the hidden field (here, to make it clear, I show this hidden field as a text box). The value of txt_json is json_string, and submit the form.
The json_encode.php file is as follows:

Copy the content to the clipboard code: <? Php
$ Json_string = $ _ POST ["txt_json"];
If (ini_get ("magic_quotes_gpc") = "1 ")
{
$ Json_string = stripslashes ($ json_string );
}
$ User = json_decode ($ json_string );
Echo var_dump ($ user );
?>

In this file, we first get the value of txt_json in the form field of POST in the json_encode.html file and put it in the variable $ json_string. Then, we can judge that if the current PHP is set to magic_quotes_gpc = On, the incoming double quotation marks will, in this way, the json_decode function cannot be parsed. Therefore, we need to reverse it. Then, use the json_decode function to convert the JSON text into an object, save it in the $ user variable, and use echo var_dump ($ user); to output the dump of the object. The final result is:

Copy the content to the clipboard code: object (stdClass) #1 (3 ){
["Name"] =>
String (10) "hanguofeng"
["Email"] =>
String (18) "example@domain.com"
["Password"] =>
String (10) "hanguofeng"
}

Json_encode function instance
In this example, json_enode.html and json_encode.php are created by two operators. In the json_decode.html file, it is basically similar to the form in the json_decode.html file, but the difference is that this time we will get the JSON text of the corresponding user from the json_encode.php file. Let's look at this PHP file first:

Copy the content to the clipboard code: <? Php
Class user
{
Public $ name = "";
Public $ email = "";
Public $ password = "";
};
$ MyUser = new user;
$ MyUser-> name = "hanguofeng ";
$ MyUser-> email = "example@domain.com ";
$ MyUser-> password = "hanguofeng ";
$ Json_string = json_encode ($ myUser );
?>
Var user = <? Php echo ($ json_string)?>;

This file first creates a class user, then obtains an instance myUser of the user class, and sets the user name, email address, and password. Then, it is converted to JSON text using the json_encode function, save the variable $ json_string and output a piece of JavaScript code to create the global variable user in JavaScript.
To add the json_encode.php file to the json_encode.html file, and obtain the attributes of the user object, as follows:

Copy the content to the clipboard code: <! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> json_encode </title>
<Script src = "json_encode.php" type = "text/javascript"> </script>
</Head>
<Body>
<Form id = "form1" name = "form1" method = "post">
<Label for = "txt_name"> name </label>
<P>
<Input type = "text" name = "txt_name" id = "txt_name"/>
</P>
<Label for = "txt_email"> email address </label>
<P>
<Input type = "text" name = "txt_email" id = "txt_email"/>
</P>
<P>
<Label for = "txt_password"> password </label>
</P>
<P>
<Input type = "text" name = "txt_password" id = "txt_password"/>
</P>
</Form>
<Script type = "text/javascript">
Document. getElementById ('txt _ name'). value = user. name;
Document. getElementById ('txt _ email '). value = user. email;
Document. getElementById ('txt _ password'). value = user. password;
</Script>
</Body>
</Html>

In this file, you need to pay attention to two points. First, we use this code to introduce the json_encode.php file as the JavaScript file:

Copy the content to the clipboard code: <script src = "json_encode.php" type = "text/javascript"> </script>

The second point is:
We add JavaScript code after the text box code to operate the value Attribute of the text box and set the value to the corresponding value of the user object respectively.
Practice
Background
Front-end JavaScript Section
PHP in the background
 

From l0m0l
 

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.