jquery - Get data from JSON array within JSON array -
i'm trying data json array within json array, having little success.
so our server returns json array within variable called 'msg', when console.log it
[{"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}]
i have following code pull out product name keep getting undefined error - uncaught typeerror: cannot read property 'prodname' of undefined
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);
any ideas i'm going wrong?
thanks
edit
i've looked @ parsed variable , get:-
[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]
so data parses fine need return data in product or object data in product separate object. ideas? thanks
try this. had fix invalid json escaping trailing quote on each
\"test product 1" <<<< \"test product 2" <<<<
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 product detail object $.each(productdetails,function(name,value) { console.log(name,value); }); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Comments
Post a Comment