JSON字符串循环问题

时间:2012-06-15 04:37:15

标签: jquery ajax arrays json

我有一个json字符串

[{"part_id":"66","part_name":"Palet crate","part_image":"crate-box.gif","0":{"language_data_content":"Length [mm]","pgd_value":"1000"},"1":{"language_data_content":"Width [mm]","pgd_value":"800"},"2":{"language_data_content":"Height [mm]","pgd_value":"800"},"3":{"language_data_content":"Thickness [mm]","pgd_value":"20"}}]

这是我在控制器中操作的Ajax响应的一部分

  for($i=0;$i<count($partlist);$i++){              
            $jsondata[$i]['part_id'] = $partlist[$i]['part_id'];
            $jsondata[$i]['part_name'] = $partlist[$i]['part_name'];
            $jsondata[$i]['part_image'] = $partlist[$i]['part_image'];
            $gdata = $pgdata->getPropertyDimensions($partlist[$i]['part_id'],1);
            if(count($gdata) > 0){
                $j = 0;
                foreach($gdata as $g){
                    $jsondata[$i][$j]['language_data_content'] = $g->language_data_content;
                    $jsondata[$i][$j]['pgd_value'] = $g->pgd_value;
                    $j++;
                }
            }           
        } 
       echo json_encode($jsondata);exit;

对于一个部分id,可以有多个 pgd_value 在这个json数组中,只有一个部分id和四个 pgd_value ..在我的ajax成功函数中循环这个json如

success:function(msg){
str = '';
  if(msg.length > 0){
                for(j=0;j<msg.length;j++){
   str +='<span>'+msg[j]['part_id']+'</span>';
   // here i want to loop those four **pgd_value** values from json is it possible ?

}
}

}

4 个答案:

答案 0 :(得分:2)

var msg = [{
    "part_id": "66",
    "part_name": "Palet crate",
    "part_image": "crate-box.gif",
    "0": {
        "language_data_content": "Length [mm]",
        "pgd_value": "1000"
    },
    "1": {
        "language_data_content": "Width [mm]",
        "pgd_value": "800"
    },
    "2": {
        "language_data_content": "Height [mm]",
        "pgd_value": "800"
    },
    "3": {
        "language_data_content": "Thickness [mm]",
        "pgd_value": "20"
    }}];
    var data = msg[0]; // extract the whole object from array
    // loop over object
    for (var key in data) {
        // checking for key which contain pgd_value
        // as you mentioned about only 4 pgd_values 
        // so here is the checking for just 4 index
        if (key == '0' || key == '1' || key == '2' || key == '3') {
            // here I used square bracket notation to 
            // retrieve data from object
            alert(data[key].pgd_value);
        }
    }

<强> DEMO

答案 1 :(得分:1)

您真的应该考虑将JSON反序列化为实际对象。它使用起来容易得多,它使您的代码更具可读性。

见这里:Deserializing from JSON into PHP, with casting?

答案 2 :(得分:1)

您可以使用jQuery.map选择pgd_values。看到这个小提琴:http://jsfiddle.net/HackedByChinese/6LLVe/1/

var str = '';
if (msg.length > 0) {
    for (j = 0; j < msg.length; j++) {
        var pgdValues = $.map(msg[j], function(item) {
            if (item['pgd_value']) return item['pgd_value'];
        });
        str += '<span> Part ID ' + msg[j]['part_id'] + ' pgd_values ' + pgdValues.join(', ') + '</span>';
        // OP: here i want to loop those four **pgd_value** values from json is it possible ?
        // ME: yep. all the IDs are now accessible from `pgdValues`


    }
}

答案 3 :(得分:1)

这应该有效。

$.each(msg,function(index,item){

    alert("Part_ID : "+item.part_id);
    alert(item[0].pgd_value)
    alert(item[1].pgd_value)
    alert(item[2].pgd_value)
    alert(item[3].pgd_value)

})

示例http://jsfiddle.net/Mc2du/29/

但是如果可能的话,尝试更改您的JSON以发送一些字符串表达式而不是0/1。因此,阅读它既简单又有力。读取索引是不安全的,因为向JSON结构添加新内容会破坏阅读代码。

假设你用这样的字符串表达式重新定义0/1方法(用Item0替换0)。你可以像这样阅读

 $.each(msg,function(index,item){
    alert("Part_ID : "+item.part_id);
    alert(item.Item1.pgd_value)
    alert(item.Item2.pgd_value)
    alert(item.Item3.pgd_value)
 })

示例:http://jsfiddle.net/Mc2du/28/