Reputation: 6941
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
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.
for (var [key,val] in jsonObj) {
console.log("Key="+key);
console.log("Value="+val);
}
for (var [key,val] of Object.entries(jsonObj)) {
console.log("Key="+key);
console.log("Value="+val);
}
Upvotes: 5
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