Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get key value from the list of JSON in NodeJS

Tags:

json

node.js

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.

like image 624
user1662039 Avatar asked Mar 07 '16 06:03

user1662039


People also ask

How do I iterate keys in JSON?

Use Object. keys() to get keys array and use forEach() to iterate over them.

How do I extract value from JSON?

To extract the name and projects properties from the JSON string, use the json_extract function as in the following example. The json_extract function takes the column containing the JSON string, and searches it using a JSONPath -like expression with the dot . notation. JSONPath performs a simple tree traversal.

Can JSON have list as value?

JSON array are ordered list of values. JSON arrays can be of multiple data types. JSON array can store string , number , boolean , object or other array inside JSON array. In JSON array, values must be separated by comma.


Video Answer


2 Answers

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]]);
}
like image 144
Florent B. Avatar answered Sep 17 '22 14:09

Florent B.


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.
}
like image 22
pride Avatar answered Sep 19 '22 14:09

pride