cody
cody

Reputation: 6941

Google Script - iterate over JSON object key value pairs

My iteration over the JSON object doesn't work as expected. What's wrong?

function handleResponse(e) {
  var jsonObj = JSON.parse(e.postData.contents);
  console.log("Note=" + jsonObj['Note'] + ", Market=" + jsonObj['Market']);
  // --> "Note=blabla, Market=flowerMarket"

  for (var [key,val] in jsonObj) {
    console.log("Key="+key); 
    console.log("Value="+val);
  }
  // --> "Key=N" "Value=o" "Key=M" "Value=a"
}

The log shows my loop takes only the first letter of the value as whole value and the second letter of the value as key. How do I get the whole key value pairs !?

Upvotes: 1

Views: 2527

Answers (2)

Tanaike
Tanaike

Reputation: 201513

In your script of for (var [key,val] in jsonObj) {}, the key is splitted with each character. And, the top 2 characters are retrieved. By this, such result is retrieved. I think that this is the reason of your issue.

If you want to retrieve the values using [key,val] in the for loop, I would like to propose the following modification.

From:

for (var [key,val] in jsonObj) {
  console.log("Key="+key); 
  console.log("Value="+val);
}

To:

for (var [key,val] of Object.entries(jsonObj)) {
  console.log("Key="+key); 
  console.log("Value="+val);
}

References:

Upvotes: 5

Cooper
Cooper

Reputation: 64100

function handleResponse(e) {
  const jsonObj = JSON.parse(e.postData.contents);
  console.log('Note= %s,Market= %s',jsonObj.Note,jsonObj.Market);
  for(let key in jsonObj) {
    console.log("Key="+key); 
    console.log("Value="+jsonObj[key]);
  }
}

Upvotes: 1

Related Questions