16

I am receiving the JSON object as a list of objects:

result=[{"key1":"value1","key2":"value2"}]

I am trying to retrieve the values from this list in Node.js. I used JSON.stringify(result) but failed. I have been trying to iterate the list using for(var key in result) with no luck, as it prints each item as a key.

Is anyone facing a similar issue or has been through this? Please point me in the right direction.

7 Answers 7

26

If your result is a string then:

var obj = JSON.parse(result);
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
  console.log(obj[keys[i]]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! if I received data as json then I do not need to generate an associative array. this answer was so appropriate. also you can write: var obj = JSON.parse(result); var keys = Object.keys(obj); keys.forEach(function (value,i) { console.log(obj[value]); }
5

Lookslike you are pointing to wrong object. Either do like

var result = [{"key1":"value1","key2":"value2"}];
for(var key in result[0]){ alert(key);}

or

var keys = Object.keys([{"key1":"value1","key2":"value2"}][0]);
alert(keys);

Comments

5

Okay, assuming that result here is a string, the first thing you need to do is to convert (deserialize) it to a JavaScript object. A great way of doing this would be:

array = JSON.parse(result)

Next you loop through each item in the array, and for each item, you can loop through the keys like so:

for(var idx in array) {
  var item = array[idx];
  for(var key in item) {
    var value = item[key];
  }
}

Comments

4

Wouldn't this just be:

let obj = JSON.parse(result);
let arrValues = Object.values(obj);

which would give you an array of just the values to iterate over.

Comments

2

A little different approach:

let result=[{"key1":"value1","key2":"value2"}]
for(let i of result){
    console.log("i is: ",i)
    console.log("key is: ",Object.keys(i));
    console.log("value is: ",Object.keys(i).map(key => i[key])) // Object.values can be used as well in newer versions.
}

Comments

1

try this code:

For result=[{"key1":"value1","key2":"value2"}]

Below will print the values for Individual Keys:

console.log(result[0].key1)

console.log(result[0].key2)

Comments

0

This is for JsonObject (not JsonArray per se). p is your jsonobject the key pairs are key and p[key]

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        console.log(key + " -> " + p[key]);
    }
}

1 Comment

Perhaps you should explain it a little bit to get a better understanding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.