var data =
[
{state:"進行中", title:"環境整治與文明勸導", type:"社區發展", peoplenum:2000},
{state:"招募中", title:"名山區攜手公益社會", type:"志願服務", peoplenum:2},
{state:"進行中", title:"環境整治與文明勸導", type:"社會公益", peoplenum:2000}
];
var html='';
html = '';';
html = '
';';
for (var i=0; i{
html = ''; ';
html = '';
html = '' data[i].title '
';
html = '招募:' data[i].peoplenum '人';
html = ' ' data[i].state;
html = '
}
html = '
html = '
$("#div1").append(html);
第一種
JSON.parse(jsonString)
第二種
eval("(" jsonString ")")
第三種
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);
根據傳回的字串可以看出是多個json拼接成的js陣列的形式。
如果傳回的只是字串鬚現將字串轉成js物件。
使用Jquery的$.each()方法循環js數組取出每個json物件的資料。
1
2
3
4
5
6
str = '[{"key":"value","keys":[{"key1":"value1","key2":"value2"},{"key1"key2":"value2"},{"key1":" ":"value4"}],"obj":{"id":1,"msg":"success"}}]';
str_json = eval("(" str ")");//將字串轉換成js物件
$.each(str_json,fucntion(a,b){
#alert(a);//彈出陣列的key
alert(b.id);//彈出要取出的資料
});
展開全部
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);
以上是如何在 JavaScript 中使用 JSON 定義變數並進行循環的詳細內容。更多資訊請關注PHP中文網其他相關文章!