Conversion of Json objects and strings details of json data splicing and JSON usage (Summary)

Source: Internet
Author: User
JSON (JavaScriptObjectNotation) is a lightweight data exchange format. this article mainly introduces how to convert Json objects and strings into json data mosaic and how to use JSON (Summary). For more information, see JSON (JavaScript Object Notation) is a lightweight data exchange format. It is based on a subset of ECMAScript. 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. Easy to read and write, and easy to parse and generate by machines (generally used to increase the network transmission rate ).

1. convert a JSON string to a JSON object: eval () and JSON. parse

Eg-json string:

Var data = '{"name": "dran", "sex": "man"}'; var obj = eval ("(" + data + ")"); or var obj = JSON. parse (data );

Then, you can read: alert (obj. name + obj. sex );

Tip: Why do you want to add ("(" + data + ")") here for eval?

The reason is: Problems with eval itself. Json starts and ends in the form of "{}". In JS, json is treated as a statement block. Therefore, it must be forcibly converted into an expression.

The purpose of parentheses is to force the eval function to forcibly convert the expressions in parentheses into objects when processing JavaScript code, rather than executing them as statements. For example, if no outer brackets are added to the object literal {}, eval identifies the braces as the start and end mark of the JavaScript code block, then {} is considered to have executed an empty statement.

2. convert a JSON object to a JSON string: obj. toJSONString () or the global method JSON. stringify (obj) (obj represents a json object)

Eg-json object: var obj = {"name": "dran", "sex": "man"}; var jstring = JSON. stringify (obj); // we recommend that you use this var jstring = obj. toJSONString (); // toJSONString () is not a native js method. You need to introduce the corresponding library or customize it before using it (not used to use it)

Then, you can read: alert (jstring );

Note:

Currently, Firefox, Opera, and IE8 and later versions also provide local JSON support. The JSON interpreter provides the following functions: JSON. parse and JSON. stringify. For browsers that do not provide local JSON support, you can introduce the json2.js script to implement the JSON conversion function. You can download the json2.js script from https://github.com/douglascrockford/json-js/blob/master/json2.js.

When AJAX implements frontend and backend data interaction, it usually uses the JSON data format. For JSON, there are strict code specifications. Once the format is incorrect, the corresponding results cannot be displayed, no error is reported in the console.

Supplement: ajax reads json data and spliced display:

Json file:

{"First": [{"name": "Zhang San", "sex": "male", "like": ["dinner", "sleeping ", "Doudou"] },{ "name": "", "sex": "male" },{ "name": "Wang Wu", "sex ": "male" },{ "name": "plum", "sex": "female" },], "second": [{"name": "Shanghai University ", "area": "Shanghai" },{ "name": "Wuhan University", "area": "Wuhan" },{ "name": "Peking University ", "area": "Beijing" },{ "name": "Shandong University", "area": "Shandong" },]}

Html and ajax code

1. Use the for Loop

$. Ajax ({url: "ceshi. json ", type:" POST ", dataType:" text ", // the browser treats the json file as a text file. Otherwise, the right policy is changed to text because the test, success: function (data) {var dataJson = eval ("(" + data + ")"); // parse json string data into the object var arr1 = dataJson. first; var arr2 = dataJson. second; // The column shows array parsing with the for loop for (var I = 0; I '+'

Name: '+ arr1 [I]. name +' Gender: '+ arr1 [I]. sex +'

'+'

School: '+ arr2 [j]. name +'

'+'

Location: '+ arr2 [j]. area +'

'+ //'

Preference: '+ arr1 [I]. like +'

'+ // Full display //'

Preference: '+ arr1 [I]. like [1] +'

'+ // Set separately //'

Preference: '+ arr1 [I]. like [0] +'

'+'

';} $ (". Result "). append (str);} // hierarchical display // var str = ""; // var str1 = ""; // if (arr1! = Null) {// for (var I = 0; I <arr1.length; I ++) {// create and assign values here // str + = "" + arr1 [I]. name + "" + arr1 [I]. sex +"
"; //} // $ (". Result "character .html (str); //} // if (arr2! = Null) {// for (var j = 0; j <arr2.length; j ++) {// str1 + = "" + arr2 [j]. name + "" + arr2 [j]. area +"
"; //} // $ (". Result2 "2.16.html (str1); // }}, error: function (data) {alert (" error ");}})

Frist:

Second:

For

2. each cyclically uses the $. each method to traverse the returned data date and insert it into the class as. result.

JSON:

[{"Name": "Michael", "sex": "male", "like": ["dinner", "sleeping", "doubebean"]}, {"name": "Li Si", "sex": "male" },{ "name": "Wang Wu", "sex": "male "}, {"name": "Li Mei", "sex": "female"},] $. ajax ({url: "ceshi. json ", type:" POST ", dataType:" text ", // the browser treats the json file as a text file. Otherwise, the right policy is changed to text because the test, success: function (data) {var dataJson = eval ("(" + data + ")"); // parse json string data into an object // use the $. the each method traverses the returned data date and inserts it into the class. in result, I indicates the index item information value object $. each (dataJson, function (I, item) {var str ='

'+'

Name: '+ item. name +' Gender: '+ item. sex +'

'+'

Like: '+ item. like +'

'+'

'; $ (". Result"). append (str) ;}, error: function (data) {alert ("error ");}})

Each

PS: for general js-generated json objects, you only need to replace the $. each () method with the for statement.

JSON data usage:

// Json object: var jsonObj = {"name": "zhangsan", "sex": "male", "age": 26,}; Use: jsonObj. name = "zhangsan" jsonObj. age = "26" // json array: [] subscript starting from 0 var jsonArr = [{"name": "Zhang San", "sex": "male ", "like": ["dinner", "sleeping", "Doudou"] },{ "name": "Li Si", "sex": "male "}, {"name": "Wang Wu", "sex": "male"},] usage: jsonArr [0]. sex = "male" jsonArr [1]. name = "" // multiple arrays: [] subscript starting from 0 var options = {"city": [{"name": "Shanghai", "area ": "Putuo District", "option": "zhenbei road", "correct": "1" },{ "name": "Shijiazhuang", "area": "Hebei ", "option": "North", "correct": "2"}], "world": [{"title": "USA", "content ": "Hollywood blockbuster sci-fi" },{ "title": "China", "content": "Love me China, although far from being"}]}; options. city [0]. area = "Putuo District" options. world [1]. content = "Love me China, although far from enough

The above section describes how to convert Json objects and strings into json data splicing and how to use JSON (Summary). I hope this will help you, if you have any questions, please leave a message and the editor will reply to you in time. I would like to thank you for your support for PHP chinnet!

For more information about Json object and String Conversion, json data splicing and JSON usage (Summary). For more information, see PHP!

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.