日期:2014-05-16  浏览次数:20345 次

查找json数据
JScript code

[
    {"id": 123, "con": "gggdfg"},
    {"id": 124, "con": "jgjjghj"},
    {"id": 125, "con": "khkhk"},
    {"id": 126, "con": "ggtyuryrty"},
    {"id": 127, "con": "dfsfsf"}
]



例如上面,我要查找id=125的con的内容应该怎么写啊

------解决方案--------------------
遍历呀
JScript code
<script>
d = [
    {"id": 123, "con": "gggdfg"},
    {"id": 124, "con": "jgjjghj"},
    {"id": 125, "con": "khkhk"},
    {"id": 126, "con": "ggtyuryrty"},
    {"id": 127, "con": "dfsfsf"}
];

for(i=0; i<(d.length); i++)
  if(d[i].id == 125) alert(d[i].con);
</script>

------解决方案--------------------
function getCon(array){
for(var i = 0;i<array.length;i++){
var obj = array[i];
if(obj.id == "125"){
return obj.con;
}
}
return null;
}
var array = [ {"id": 123, "con": "gggdfg"}, {"id": 124, "con": "jgjjghj"}, {"id": 125, "con": "khkhk"}, {"id": 126, "con": "ggtyuryrty"}, {"id": 127, "con": "dfsfsf"} ]
var result = getCon(array);
alert(result);
------解决方案--------------------
JScript code

    var t2 = [
    {"id": 123, "con": "gggdfg"},
    {"id": 124, "con": "jgjjghj"},
    {"id": 125, "con": "khkhk"},
    {"id": 126, "con": "ggtyuryrty"},
    {"id": 127, "con": "dfsfsf"}
];
var myobj=eval(t2);
for(var i=0;i<myobj.length;i++){
   alert(myobj[i].id);
   alert(myobj[i].con);
}

------解决方案--------------------
如果你的结构就是这样的两个元素,而且每个ID都不重复,为了以后随时取用某个ID的CON,我建议可以加这个数据存储到一个关联数组中
 
JScript code

      var arr1 = [
    { "id": 123, "con": "gggdfg" },
    { "id": 124, "con": "jgjjghj" },
    { "id": 125, "con": "khkhk" },
    { "id": 126, "con": "ggtyuryrty" },
    { "id": 127, "con": "dfsfsf" }
];
    var arr2 = new Array;
    for (var i = 0; i < arr1.length; i++) {
        arr2[arr1[i]["id"]] = arr1[i]["con"];
    }
    alert(arr2["125"]);