user1662039
user1662039

Reputation: 329

Get key value from the list of JSON in NodeJS

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.

Upvotes: 16

Views: 95516

Answers (7)

DragonFire
DragonFire

Reputation: 4082

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]);
    }
}

Upvotes: 0

pride
pride

Reputation: 85

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.
}

Upvotes: 2

Avalanchd
Avalanchd

Reputation: 126

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.

Upvotes: 4

Shiva
Shiva

Reputation: 39

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)

Upvotes: 1

Chitharanjan Das
Chitharanjan Das

Reputation: 1333

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];
  }
}

Upvotes: 5

Florent B.
Florent B.

Reputation: 42518

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]]);
}

Upvotes: 26

vinayakj
vinayakj

Reputation: 5681

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);

Upvotes: 5

Related Questions