Home > Article > Computer Tutorials > How to define variables and loop using JSON in JavaScript
var data =
[
{state: "In Progress", title: "Environmental Improvement and Civilized Persuasion", type: "Community Development", peoplenum:2000},
{state: "Recruiting", title: "Mingshan District Joins Hands with Public Welfare Society", type: "Volunteer Service", peoplenum:2},
{state: "In Progress", title: "Environmental Improvement and Civilized Persuasion", type: "Social Welfare", peoplenum:2000}
];
var html='';
html = '';';
html = '
';';
for (var i=0; i{
html = ''; ';
html = '';
html = '' data[i].title '
';
html = 'Recruitment:' data[i].peoplenum 'people';
html = ' ' data[i].state;
html = '
}
html = '
html = '
$("#div1").append(html);
The first
JSON.parse(jsonString)
Second type
eval("(" jsonString ")")
The third type
var obj=(function ToJSON(o){
if(typeof(o)=="string")try{return new Function("return " o)();}catch(e){return null;}
})("[{name:'zhangsan',age:'24'},{name:'lisi',age:'30'},{name:'wangwu',age:'16'}, {name:'tianqi',age:'7'}]");
for(var b in obj)alert(obj[b].name);
According to the returned string, it can be seen that it is in the form of a js array spliced into multiple jsons.
If only a string is returned, the string must be converted into a js object.
Use Jquery's $.each() method to loop through the js array to retrieve the data of each json object.
1
2
3
4
5
6
str = '[{"key":"value","keys":[{"key1":"value1","key2":"value2"},{"key1":"value3","key2 ":"value4"}],"obj":{"id":1,"msg":"success"}}]';
str_json = eval("(" str ")"); //Convert string into js object
$.each(str_json,fucntion(a,b){
alert(a); //Pop up the key of the array
alert(b.id);//Pop up the data to be taken out
});
Expand All
var result = [];
var item =[
{
"resource_id":'',
"text":'',
"content_desc": '',
"smallImg":'',
"existFlag":true
},
{
"resource_id":'7886',
"text":'454',
"content_desc": '45',
"smallImg":'132',
"existFlag":true
},
{
"resource_id":'7886',
"text":'454',
"content_desc": '45',
"smallImg":'132',
"existFlag":true
},
{
"resource_id":'aaa',
"text":'bbb',
"content_desc": 'ccc',
"smallImg":'ddd',
"existFlag":true
},{
"resource_id":'',
"text":'',
"content_desc": '',
"smallImg":'',
"existFlag":true
}
];
for(var i=0;i var obj=item[i];
if(!!obj["resource_id"]){
result.push(obj);
}
}
console.log(result);
The above is the detailed content of How to define variables and loop using JSON in JavaScript. For more information, please follow other related articles on the PHP Chinese website!