-1

I have this JSON:

[[{"product_name":"prod-1","product_url":"http:\\www.google.com"}]]

CODE JS:

 var giftLabel = window.checkout.giftLabel; // return json

 var array = JSON.parse("[" + giftLabel + "]"); // transform in a array

 for(var i = 0; i < array.length; i++) {
        for(var j = 0; j < array[i].length; j++) {
            var parse = JSON.parse(array[i][j]);   //this line not working
            console.log(parse.product_name);       //this line not working
        }
    }

I want to extract the values from this JSON and choose an example

OUTPUT:

prod-1
http:\\www.google.com

Can you please tell me where I am wrong and why can't I extract the values from JSON correctly?

Cristi
  • 531
  • 1
  • 8
  • 21
  • 1
    first thing `giftLabel` is not json string its a array .so no need to parse – prasanth Nov 07 '19 at 10:05
  • Like @prasanth said, `[[{"product_name":"prod-1","product_url":"http:\\www.google.com"}]]` is an **array**, not a `json` – Roy Bogado Nov 07 '19 at 10:06
  • Why are you adding `[]` around a JSON string which already has 2 `[]` wrapped around it? Just `JSON.parse(giftLabel)`. Remove the `JSON.parse` from inside the loop – adiga Nov 07 '19 at 10:11
  • See this [codesandbox](https://codesandbox.io/s/pedantic-satoshi-ogr7s) – Karl Taylor Nov 07 '19 at 10:17

3 Answers3

0

It seem your [[{"product_name":"prod-1","product_url":"http:\\www.google.com"}]] is already in JS object. So you can always access it via

var x = [[{"product_name":"prod-1","product_url":"http:\\www.google.com"}]];

console.log(x[0][0].product_name);

Or if you value is in JSON text, then parse it first:

var x = JSON.parse("you json text");

then continue as above example.

Here's the working in loop:

var x = JSON.parse("json  text");

x.forEach(function(i){
    i.forEach(function(ii)){
          console.log(ii.product_name);
    }

});
Mr Hery
  • 829
  • 1
  • 7
  • 25
0
var parse = array[i][j];
output = Object.values(parse)

output = ['prod-1', 'http:\www.google.com']

Object.values will return an array of all the values inside the passed object

H.Hinn
  • 73
  • 2
  • 7
0

let d = [
  [{
    "product_name": "prod-1",
    "product_url": "http:\\www.google.com"
  }]
]

for (let i = 0; i < d.length; i++) {
  for (let j = 0; j < d[i].length; j++) {
    if(typeof d[i][j] != "undefined"){
    console.log(d[i][j]["product_name"]);
    console.log(d[i][j]["product_url"]);
}
  }
}
Kaushik
  • 2,072
  • 1
  • 23
  • 31