JSON objects and strings convert JSON data concatenation and JSON usage details (summary) _javascript tips

Source: Internet
Author: User
Tags eval opening and closing tags sleep

JSON (JavaScript Object notation) is a lightweight data interchange format. It is based on a subset of ECMAScript. JSON uses a completely language-independent text format, but it also uses a family of C-language (c, C + +, C #, Java, JavaScript, Perl, Python, and so on). These features make JSON an ideal data exchange language. Easy to read and write, but also easy to machine parsing and generation (generally used to improve network transmission rate).

One, JSON string converted to 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 this: alert (Obj.name + obj.sex);

Hint: Why eval here to add ("(" +data+ ")");

The reason is that eval itself is a problem. Since JSON starts and ends with "{}", in JS it is treated as a block of statements, so it must be coerced into an expression.

The purpose of parentheses is to force the Eval function to force an expression in parentheses (expression) into an object when processing JavaScript code instead of executing as a statement (statement). For example, an object literal {}, if the outer bracket is not added, then eval recognizes the curly braces as the opening and closing tags of the JavaScript code block, then {} will be considered to have executed an empty statement

Second, the JSON object is converted to a JSON string: obj.tojsonstring () or global method Json.stringify (obj) (obj represents the JSON object)

Eg-json object: var obj = {"Name": "Dran", "Sex": "Man"};
var jstring = json.stringify (obj);/recommended with this
var jstring = obj.tojsonstring ();//tojsonstring () is not a JS native method. You need to introduce the appropriate library or define it yourself before you can use it (not used to)

Then, you can read it like this: alert (jstring);

Attention:

At present, Firefox, Opera, IE8 version of the above also provides local JSON support.   Among the functions provided by the JSON interpreter are: Json.parse, json.stringify. For browsers that do not provide local JSON support, you can introduce script json2.js to implement the JSON conversion functionality. Json2.js scripts can be downloaded to the Https://github.com/douglascrockford/JSON-js/blob/master/json2.js page

In the AJAX implementation of data interaction before and after, usually using JSON data format, for JSON, there are strict code specifications, once the format problem, you will not be able to display the corresponding effect, but not the console error

Add: Ajax reads JSON data stitching display:

JSON file:

{' A '
: [
{' name ': ' John "," Sex ":" Male "," like ": [" Eat "," sleep "," Dozen Peas "]},
{" name ":" Dick "," Sex ":" Male "},
{" Name " : "Wang Wu", "Sex": "Male"},
{"name": "Li Mei", "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 for loop

$.ajax ({url: "Ceshi.json", type: "POST", DataType: "Text",//browser will not read the JSON file as a text file) the expedient is changed to text because the test, JSON file format correct book Write Success:function (data) {var Datajson = eval ("+data+");//parse JSON string data into object var arr1 = Datajson.first; var arr2 = d
Atajson.second; The column displays the array resolution for the For loop (var i = 0; i<arr1.length; i++) {for (var j = 0; j<arr2.length; j +) {var str= ' <div style= "Display:block" > ' + ' <div> name: ' +arr1[i].name+ ' sex: ' +arr1[i].sex+ ' </div> ' + ' <div> school: ' +arr2[j '. Name+ ' </div> ' + ' <div> location: ' +arr2[j].area+ ' </div> ' +//' <div> preferences: ' +arr1[i].like+ ' </div> ' +//Full show//' <div> preferences: ' +arr1[i].like[1]+ ' </div> ' +//Individual settings//' <div> preferences: ' +arr1[i].like[0]+ ' </div
> ' + ' </div> ';
} $ (". Result"). Append (str);
}//layered display//var str = "";
var str1 = ""; if (arr1!= null) {//for (var i = 0; i < arr1.length; i++) {//All of which are created and assigned/STR + + "<span>" + arr1[i].name + "</span><span>" + arr1[i].sex + "</span><br> ";
}//$ (". Result"). html (str); }//if (arr2!= null) {//for (var j = 0 J < Arr2.length; J + +) {//str1 + + "<span>" + Arr2[j].name + "<
/span><span> "+ arr2[j].area+" </span><br> ";
}//$ (". Result2"). HTML (STR1); 
}, Error:function (data) {alert ("error"); }}) <div class= "result" >frist:</div> <div class= "RESULT2" >second:</div> for

2. Each loop uses the $.each method to traverse the returned data date, inserted into class.

Json:

[
{' name ': ' John ', ' sex ': ' Male "," like ": [" Eat "," sleep "," Dozen Peas "]},
{" name ":" Dick "," Sex ":" Male "},
{" name ":" Wang Wu "," Sex ":" Male "},
{" name ":" Li Mei "," Sex ":" Female "},
]
$.ajax ({
URL:" Ceshi.json ",
Type:" POST ", 
dataType:" Text "//browser will not read the JSON file as a text file otherwise the expediency is changed to text because the test, the JSON file format is correctly written
success:function (data) { 
var Datajson = eval (" ("+data+") "); Parse the JSON string data into an object
//each loop using the $.each method to traverse the returned data date, insert into class. I represents the index item information value Object 
$.each (Datajson, function (I,item) {
var str= ' <div style= ' display:block ' > ' +
' <div> name: ' +item.name+ ' sex: ' + item.sex+ ' </div> ' +
' <div>like: ' +item.like+ ' </div> ' +
' </div> '; 
$ (". Result"). Append (str);} 
)
},
error:function (data) {
alert ("error"); 
}
)
<div class= "Result" ></div>

PS: For the general JS generation JSON object, only need to replace the $.each () method with the For statement, the other unchanged

How to use JSON data:

JSON objects:
var jsonobj= {
"name": "John",
"sex": "Male",
"age": N,
};
Use: Jsonobj.name= "John"
jsonobj.age= "
//json array: [] subscript starting from 0
var jsonarr =[
{" name ":" John "," Sex ":" Male " , "like": ["Eat", "Sleep", "Beat Peas"]},
{"name": "Dick", "Sex": "Male"},
{"name": "Wang Wu", "Sex": "Male"},
]
use: Jsonarr [0].sex= "Male"
jsonarr[1].name= "Dick"
//Multiple arrays: [] subscript starting from 0
var options = {"City
": [
{ 
"name":] "Shanghai",
"area": "Putuo",
"option": "True North Road",
"correct": "1"
},
{
"name": "Shijiazhuang",
"area" : "Hebei",
"option": "In the North",
"correct": "2"
}],
"World": [
{
"title": "The United States",
"content "": "Hollywood blockbuster science Fiction"
},
{"
title": "China",
"content": "Love my Chinese, although far will punish"
}
;
Options.city[0].area= "Putuo District"
options.world[1].content= "Love my Chinese, although far will be

The above is a small set for you to introduce the JSON object and string conversion JSON data splicing and JSON usage details (summary), I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.