JSON object and array object

Source: Internet
Author: User

I,Brief Introduction to JSON
In terms of structure, all data can be divided into three types:

 
The first type is scalar (scalar), which is a separate string or number (numbers), such as the word "Beijing.
The second type is sequence (sequence), that is, several related data are listed in a certain order, also called array or list, for example, "Beijing, tokyo ".
The third type is mapping, that is, a name/value pair (name/value), that is, the data has a name and a value corresponding to it, this is also called hash or dictionary, for example, "capital: Beijing ".

JSON (JavaScript Object Notation) is a lightweight data exchange format. Its rules are simple and interesting:
1) Separate the parallel data with commas.
2) The ing is represented by the colon.
3) The set (array) of the parallel data is represented by square brackets.
4) The ing set (object) is represented by braces.

 

According to this rule, we can understand the following:
1. an array is created with "[]", an object is created with "{}", and JSON is basically an array or object created with [] or, otherwise, a normal string is meaningless;
2. Elements of arrays and objects are separated by commas;
3. Inside the object, the (attribute) names and values are separated by ":" and must be separated by ":". Attribute names or values cannot exist separately;
4. objects and arrays can be nested, that is, an element in an array can be an object or an array. Likewise, the value of an attribute in an object can be an object or an array.

 

Ii. Case Description
1.
VaR China = {Beijing: {name: "Beijing", Area: "16000", Haidian: {name: "Haidian District "}},
Shanghai: {name: "Shanghai", Area: "10000", Minhang: {name: "Minhang District "}}};
Alert (China. Beijing. Haidian. Name );
Alert (China. Shanghai. Minhang. Name );
"Haidian District" and "Minhang District" are displayed respectively ".

2.
VaR ourcountry = [["Beijing"], ["Shanghai"], ["Hefei", "Wuhu", "Bengbu"];
Alert (ourcountry [2] [1]);
Wuhu City

3.
VaR Zhongguo = {provinces: [{name: "Beijing", cities: [{name: "Beijing", quxian: ["Haidian District", "Chaoyang District", "Dongcheng District ", "Xicheng district"]},
{Name: "Anhui Province", cities: [{name: "Wuhu City", quxian: ["fanchang county", "Wuhu County", "Nanling County", "Sanshan district"]}, {name: "Hefei", quxian: ["Feixi county", "Shushan district", "luyang district"]},
"Hubei Province"
]};

VaR STR = "China: {\ n ";
For (VAR I = 0; I <Zhongguo. Provinces. length; I ++)
{
If (Zhongguo. Provinces. Cities! = NULL)
{
STR + = Zhongguo. Provinces. Name + "{";
For (var j = 0; j <Zhongguo. Provinces. Cities. length; j ++)
{
If (Zhongguo. Provinces. Cities [J]! = NULL)
{
STR + = Zhongguo. Provinces. Cities [J]. Name + "{";
For (var k = 0; k <Zhongguo. Provinces. Cities [J]. quxian. length; k ++)
{
STR + = Zhongguo. Provinces. Cities [J]. quxian [k];
If (K! = Zhongguo. Provinces. Cities [J]. quxian. Length-1)
{
STR + = ",";
}
}
STR + = "}";
}
}
STR + = "} \ n ";
}
}
STR + = "}";
Alert (STR );
"
China :{
Beijing {Haidian District, Chaoyang district, Dongcheng District, Xicheng district }}
{Wuhu City {fanchang County, Wuhu County, Nanling County, Sanshan district} Hefei {Feixi County, Shushan district, luyang district }}
}
".

 

 

 

Iii. Application of JSON in Ajax
The client can easily submit data to the server through the address bar or post. However, after the server completes data processing, it is difficult to return the computing result information to the client, especially when the data volume is large. At this time, the data format becomes the key. According to a specific format, data can be easily assembled and then parsed conveniently. JSON is a good strategy. On the server side, a string is assembled in JSON format and returned to the client. How do I parse the client? Generally, there are two policies (the names of these two policies are self-Assigned Names, which are not necessarily reasonable, but the idea should be correct ):

 
1. Direct Parsing
VaR JSON = eval ('+ Result + ')');
Through the above expression, the JSON string that the server returns to the client is parsed into a JSON (Format) object named "JSON" and passed "JSON. or "JSON.

2. Indirect Parsing
VaR JSON = "r =" + result;
Eval (JSON );
Of course, the above line of code can be merged into: eval ("r =" + result );
Through the above calculation, you can also parse the JSON string returned by the server to the client into a JSON (Format) object, but the object name is "r ", through "R. or "R.
Summary: JSON is a simple data exchange format. It can replace XML to allow flexible data exchange between servers.

 

Iv. arrays and objects in Javascript

In JavaScript, the data format created by [] is usually called an array, and what is created by {} is called an object.
There is an array A = [,], and an object A = {,}, run alert (A [1]), in both cases, the running results are the same! This means that the data set can be represented by arrays or objects. Which one should it be used?
In fact, arrays represent the set of ordered data, and objects represent the set of unordered data. If the order of data is important, use an array. Otherwise, use an object.
Of course, another difference between an array and an object is that the data in the array does not have a "name" and the data in the object has a "name ). But the problem is that many programming languages have something called associativearray. The data in this array is named. For example, in Javascript, you can define an object as follows:
VaR A = {"city": "Beijing", "area": 16800, interesting, "Population": 1600 };
However, it can also be defined as an associated array:
VaR A = new array ();
A ["city"] = "Beijing ";
A ["area"] = 16800;
A ["Population"] = 1600;
In this way, it seems that there is no difference between arrays and collections. Actually, no. In JavaScript, an associated array is an object, and an object is an associated array. There is a big difference between an array created in the second method and an array created in the [] method. In the "array" created in the second method, you can also use the ". city to get "Beijing", ". population "to get" 1600 ", but it is different from the object created in the first method. The first method defines a without the Length attribute, second, the second method defines a as yes, but the value is 0. The difference is still visible. To be specific, I'm afraid I have to look at some of the underlying implementation code.

When the JSON value returned by Eval is returned, error: Invalid label abstract is displayed. We often return a value in JSON format on the server side, which can be directly used as a complete object in the script, however, many new users usually encounter an error message: Invalid label, which is often annoying because the JSON format is correct but prompts an error. If you encounter this problem, please take a look at the content of this article!

We often return a value in JSON format on the server side, which can be directly used as a complete object in the script. However, many new users usually encounter an error message: Invalid label, this problem is often distressing, because the correct JSON format is prompted with an error.

Assume that you return a JSON string from the server:
>
Run the following command in eval mode in the script:
>
The following message is displayed:Error: Invalid label
In fact, our JSON format is not incorrect, but when Eval is used, you should enclose your JSON value in brackets:
> Var result = eval ("(" + O. responsetext + ")"); help001

 

V. JSON parsing by JS

 

JSON (JavaScript Object Notation) is a lightweight data exchange format. It adopts a completely language-independent text format and is an ideal data exchange format. JSON is a native JavaScript format, which means that no special API or toolkit is required to process JSON data in JavaScript.

This article mainly summarizes the essentials for JS operations on JSON.

In JSON, there are two structures: objects and arrays.

1. An object starts with "{" (left parenthesis) and ends with "}" (right Parenthesis. Each "name" is followed by a ":" (colon); "," (comma) is used to separate the "name/value" pairs. The name is enclosed in quotation marks. If the value is a string, it must be enclosed in parentheses, but not numeric. For example:

VaR o = {"xlid": "cxh", "xldigitid": 123456, "topscore": 2000, "topplaytime "};

2. An array is an ordered set of values. An array starts with "[" (left square brackets) and ends with "]" (right square brackets. Values are separated by commas.

For example:

VaR jsonranklist = [{"xlid": "cxh", "xldigitid": 123456, "topscore": 2000, "topplaytime": "" },{ "xlid ": "ZD", "xldigitid": 123456, "topscore": 1500, "topplaytime": "2009-11-20"}];

JSON provides a JSON. js package: http://www.json.org/json.js for easy processing of JSON data.

In the data transmission process, JSON is transmitted in the form of text, that is, strings, while JS operates on JSON objects. Therefore, the conversion between JSON objects and JSON strings is the key. For example:

JSON string:

VaR str1 = '{"name": "cxh", "sex": "Man "}';

JSON object:

VaR str2 = {"name": "cxh", "sex": "Man "};

1. convert a JSON string to a JSON object

To use str1 above, you must use the following to convert to a JSON object first:

// Converts a JSON string to a JSON object

VaR OBJ = eval ('+ STR + ')');

Or

VaR OBJ = Str. parsejson (); // converts a JSON string to a JSON object.

Or

VaR OBJ = JSON. parse (STR); // converts a JSON string to a JSON object.

Then, you can read:

Alert (obj. Name );

Alert (obj. Sex );

NOTE: If obj is a JSON object, it is still a JSON object after eval () function conversion (even Multiple conversions), but parsejson () is used () after the function is processed, there will be questions (a syntax exception is thrown ).

2. You can use tojsonstring () or the global essentials JSON. stringify () to convert a JSON object to a JSON string.

For example:

VaR last = obj. tojsonstring (); // converts a JSON object to a JSON character

Or

VaR last = JSON. stringify (OBJ); // converts a JSON object to a JSON character

Alert (last );

Note:

Among the above multiple essentials, except that the eval () function is provided by JS, all other essentials come from the JSON. js package. The new JSON version modifies the API and changes JSON. stringify () and JSON. the two essentials of parse () are injected into the built-in JavaScript Object. The former becomes the object. tojsonstring (), and the latter is a string. parsejson (). If you cannot find the tojsonstring () and parsejson () essentials, it indicates that your JSON package version is too low.

6. gson operations on objects

Gson and other existing Java JSON class libraries are the largest and different. gson needs to serialize the real class and does not need to use annotation to identify the fields to be serialized, at the same time, gson can use annotation to flexibly configure fields to be serialized.

The operations in Java are as follows:

Gson =
New gson ();
List <person> Persons
= New arraylist <person> ();
For (INT I
= 0; I
<10; I ++ ){
Person P =
New person ();
P. setname ("name"
+ I );
P. setage (I *
5 );
Persons. Add (P );
}
String STR = gson. tojson (persons );

Next let's take a look at the deserialization of gson. gson provides the fromjson () method to implement methods from JSON-related objects to Java entities.

In daily applications, we usually encounter two situations: convert to a single object, convert to an object list or another structure.

First, let's look at the first one:

For example, the JSON string is [{"name": "name0", "Age": 0}]

Code:

Person person = gson.fromJson(str, Person.class);

Two parameters are provided, which are a JSON string and the type of the object to be converted.

Second, convert to list type:

Code:

List<Person> ps = gson.fromJson(str, new TypeToken<List<Person>>(){}.getType());for(int i = 0; i < ps.size() ; i++){     Person p = ps.get(i);     System.out.println(p.toString());}

We can see that the above Code uses typetoken, a data type converter provided by gson, which supports conversion of various data sets.

 

 

 

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.