从JSON数组中的JSON数组中获取数据

时间:2015-04-29 12:39:09

标签: jquery arrays json

我正在尝试从JSON数组中的JSON数组中获取数据,但收效甚微。

所以我们的服务器在名为'msg'的变量中返回一个JSON数组,当我在console.log中时它看起来像这样。

[{"product":"[{\"imgUrl\":\"/p/332401\",\"prodCartQty\":2,\"prodName\":\"Test Product 1",\"productCode\":\"332401\"},{\"imgUrl\":\"/p/332388\",\"prodCartQty\":2,\"prodName\":\"Test Product 2",\"productCode\":\"332388\"}]","category":"gross_MAX_1","totalCategory":1},{"product":"[{\"imgUrl\":\"/p/332401\",\"prodCartQty\":2,\"prodName\":\"Test Product 1",\"productCode\":\"332401\"},{\"imgUrl\":\"/p/332388\",\"prodCartQty\":2,\"prodName\":\"Test Product 2",\"productCode\":\"332388\"}]","category":"gross_MAX_1","totalCategory":1}]

然后我有以下代码来提取产品名称,但一直得到一个未定义的错误 - 未捕获的TypeError:无法读取未定义的属性'prodName'

console.log(msg);
var data = $.parseJSON(msg);
console.log(data);

OBJ = {};
OBJ.apply = function(data) {
    $.each(data, function() {
        $.each(this, function(key, value) {
            console.log(value.product.prodName);
        });
    });
};
OBJ.apply(data);

我出错的任何想法?

由于

修改

我查看了解析后的变量,得到了: -

[Object, Object]
0: Object
category: "restrictedItems_ie-standard-gross_MAX_1"
product: "[{"imgUrl":"/p/332401","prodCartQty":2,"prodName":"Test Product 1","productCode":"332401"},{"imgUrl":"/p/332388","prodCartQty":2,"prodName":"Test Product 2","productCode":"332388"}]"
totalCategory: 1
__proto__: Object
1: Object
category: "restrictedItems_ie-standard-gross_MAX_1"
product: "[{"imgUrl":"/p/332401","prodCartQty":2,"prodName":"Test Product 1","productCode":"332401"},{"imgUrl":"/p/332388","prodCartQty":2,"prodName":"Test Product 2","productCode":"332388"}]"
totalCategory: 1
__proto__: Object
length: 2
__proto__: Array[0]

因此数据解析得很好但现在我需要返回产品中的数据或将Product中的对象数据转换为单独的对象。 有任何想法吗?感谢

2 个答案:

答案 0 :(得分:0)

看起来需要unescaped

如果您将JSON粘贴到this JSON formatter之类的工具中,您将能够更清楚地看到它与\的不同之处。

答案 1 :(得分:0)

试试这个。我必须通过转义每个

上的尾随引号来修复无效的JSON
\"Test Product 1" <<<<
\"Test Product 2" <<<<

&#13;
&#13;
var data = [
    {
        "product": "[{\"imgUrl\":\"/p/332401\",\"prodCartQty\":2,\"prodName\":\"Test Product 1\",\"productCode\":\"332401\"},{\"imgUrl\":\"/p/332388\",\"prodCartQty\":2,\"prodName\":\"Test Product 2\",\"productCode\":\"332388\"}]",
        "category": "gross_MAX_1",
        "totalCategory": 1
    },
    {
        "product": "[{\"imgUrl\":\"/p/332401\",\"prodCartQty\":2,\"prodName\":\"Test Product 1\",\"productCode\":\"332401\"},{\"imgUrl\":\"/p/332388\",\"prodCartQty\":2,\"prodName\":\"Test Product 2\",\"productCode\":\"332388\"}]",
        "category": "gross_MAX_1",
        "totalCategory": 1
    }
]



$.each(data,function(_,productArr) {
  var arr = JSON.parse(productArr.product.replace(/\//g,""));
  $.each(arr,function(_,productDetails) {
    // here is a product detail object
    $.each(productDetails,function(name,value) {
      console.log(name,value);
    });
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
&#13;
&#13;