Introduction to the operation of JSON in JavaScript

Source: Internet
Author: User
Tags arrays eval string to json

JSON syntax
JSON is constructed in two structures:
Object-A collection of name/value pairs. In different languages, it is understood as objects, records, structures, dictionaries, hash tables, a list of keys (keyed list), or associative arrays. An object begins with "{" (opening parenthesis), and "}" (closing parenthesis) ends. Each "name" is followed by a ":" (a colon), and the ' name/value ' pair is separated by a ', ' (comma).
Array-an ordered list of values. In most languages, it is understood as an array. An array begins with "[" (left bracket), and "]" (right bracket) ends. Values are separated by the "," (comma) value.
JSON has no variables or other control structures. JSON is used only for data transfer.


This article is mainly on the JS operation of the JSON method to do the summary.

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

1. An object begins with "{" (opening parenthesis), and "}" (closing parenthesis) ends. Each "name" is followed by a ":" (a colon), and the ' name/value ' pair is separated by a ', ' (comma). The name is enclosed in quotation marks; If the value is a string, it must be in parentheses, and the numeric type is not required.

For example:

The code is as follows Copy Code
var o={"Xlid": "Cxh", "Xldigitid": 123456, "Topscore": "," Topplaytime ":" 2009-08-20 "};


2. An array is an ordered set of values (value). An array begins with "[" (left bracket), and "]" (right bracket) ends. Values are separated by the "," (comma) value.

For example:

The code is as follows Copy Code

var jsonranklist=[{"Xlid": "Cxh", "Xldigitid": 123456, "Topscore": ", Topplaytime": "2009-08-20"},{"Xlid": "Zd", " Xldigitid ": 123456," Topscore ": 1500," Topplaytime ":" 2009-11-20 "}];

To facilitate processing of JSON data, JSON provides a json.js package for downloading addresses:

Http://www.json.org/json.js

In the process of data transfer, JSON is passed in the form of text, the string, and JS is the JSON object, so the conversion between the JSON object and the JSON string is the key. For example:
JSON string:

The code is as follows Copy Code
var str1 = ' {' name ': ' cxh ', ' sex ': ' Man '} ';
JSON object:
var str2 = {"Name": "Cxh", "Sex": "Man"};


One, JSON string converted to JSON object

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

The code is as follows Copy Code

Convert from JSON string to JSON object

var obj = eval (' (' + str + ') ');

Or

var obj = Str.parsejson (); Convert from JSON string to JSON object

Or

var obj = json.parse (str); Convert from JSON string to JSON object

Then, you can read this:

The code is as follows Copy Code

Alert (Obj.name);

Alert (Obj.sex);

Special Note: If obj is a JSON object, then using the eval () function to convert (even multiple conversions) is a JSON object, but there is a problem with using the Parsejson () function (throwing a syntax exception).

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

The code is as follows Copy Code

For example:

var last=obj.tojsonstring (); Convert a JSON object to a JSON character

Or

var last=json.stringify (obj); Convert a JSON object to a JSON character

alert (last);


String object into a JSON object
function Stringtojson (stringvalue)
{
Eval ("var thejsonvalue =" +stringvalue);
return thejsonvalue;
}

4:json the method of converting an array to a string object (to get rid of the method above)

function Jsonarraytostringcfz (Jsonarray)

var jsonarraystring = "[";
for (Var i=0;i<jsonarray.length;i++) {
JSONARRAYSTRING=JSONARRAYSTRING+JSONTOSTRINGCFZ (Jsonarray[i]) + ",";
}
jsonarraystring = jsonarraystring.substring (0,jsonarraystring.length-1) + "]";
return jsonarraystring;
}

5 using json.js json to go to string

<script src= "Json2.js" ></script>
<script>
var date = {Myarr: ["A", "B", "C", "D"], count:4};
var str = json.stringify (date);
alert (str);
</script>

To create a JSON data request using the XMLHttpRequest object
1. Create request
If you directly request JSON data from the server's previous JSON file, you can use the filename to request the JSON file.

The code is as follows Copy Code
Respone.open ("Get", "Classes.txt", true);

      in this case, Classes.txt is the name of the JSON data file, which is creating a variable to hold the XMLHttpRequest object.
      2, parse response
      Once you accept the server's JSON data, you can resolve the response in two different ways. You can use the built-in functions of JavaScript to Eval (), or use the JSON parser instead for further security. The
      eval () method can take a JavaScript string as an argument, or you can convert the string to an object or act as a command. If you request JSON data using the XMLHttpRequest object's ResponseText property, use eval () to convert the JSON text string to a JavaScript object. Because the JSON string often contains curly braces, enclose the JSON string with parentheses to indicate that the word is an evaluation expression, not a command to run.

The code is as follows Copy Code
var Jsonresp=request.responsetext;
Jsonresp=eval ("(" +jsonresp+ ")");

The eval () method is appropriate if the Web server provides both JSON data and a request page. If security is involved, it is appropriate to use the JSON parser. The JSON parser acts only on JSON text and does not perform other JavaScript. In this case, you can use ResponseText, but use the Parsejson () method to convert the JSON text string into a JavaScript object. To access the PARSEJOSN function, you need to add a reference json.js file to the page.

The code is as follows Copy Code
var Jsonresp=request.responsetext;
Jsonresp=jsonresp.parsejson ();

Here's an example to illustrate the simple use of JSON in javascript:

The code is as follows Copy Code
<script type= "Text/javascript" >
var user =[
{
"Name": "Shenmiweiyi",
"QQ": 306451129,
"Email": "shenmiweiyi@163.com"
"Address":
[
{"City": "Zhengzhou", "ZipCode": "450000"},
{"City": "BeiJing", "ZipCode": "100000"}
]
},
{
"Name": "Kehao",
"QQ": 254892313,
"Email": "kehao@163.com"
"Address":
[
{"City": "Shanghai", "ZipCode": "200000"},
{"City": "Guangzhou", "ZipCode": "510000"}
]
}
]
Alert (user[0].name+ "email is:" user[0].email); Outputs Shenmiweiyi's email is: shenmiweiyi@163.com
Alert (user[1].name+ "live in:" User[1].address[0].city)//outputs Kehao live in: Shanghai
</script>
Related Article

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.