Create a JSON object in JS:
1. Defining JSON objects directly
var employees ="firstName": "Bill", "LastName": "Gates""firstName": "George", "LastName": " Bush "firstName": "Thomas", "LastName": "Carter" }];
alert (employees[0].firstname); You can see the output as Bill
2. By stitching the string and then converting it to a JSON pair image.
Example 1:
1 varids=["1", "2", "3"];2 varnames=["One", "one", "three"];3 4 varJson= "[";5 for(vari=0;i<ids.length;i++){6json+={"id": ids[i], "name": Names[i]};7 if(i+1<ids.length) json+= ",";8 }9json+= "]";Ten Onejson=Json.parse (JSON); AAlert (json[0]); -}
The above example 1 will be 11 Rows Json.parse (JSON); error. because Json.parse () This method can only convert a string to a JSON object. In the example above, JSON is not stitched as a string in line 6th, but in line 4th, JSON is a string concatenation. Part of this JSON variable is a string, part of an object, This is not a JSON string, so it resolves an error.
Json.parse () Usage:
var foo = ' [{' id ': ' 1 ', ' name ': ' "'"}] ';
var json2=json.parse (foo);
Alert (json2[0].id)
Foo is a string, so the conversion is correct.
Example 1 is changed to read as follows:
var ids=["1", "2", "3"var names=["One", "one", "three"var json= "[" for (var i=0;i<ids.length;i++) { json+ = ' {"id": \ "' +ids[i]+ ' \", "name": \ "' + names[i]+ ' \ '} '; if (i+1<ids.length) json+= ","; } json+ = "]"; alert (JSON); JSON=json.parse (JSON); Alert (json[0].id);
Convert the JSON stitching in the loop body to a string, so it's OK.
Create json/conversion string in JavaScript as JSON