Get key value from the list of JSON in NodeJS - json

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.

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

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

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

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.

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

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)

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

Related

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 !?
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:
for...in
for...of
Object.entries()
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]);
}
}

How to get nested deep property value from JSON where key is in a variable?

I want to bind my ng-model with JSON object nested key where my key is in a variable.
var data = {"course":{"sections":{"chapter_index":5}}};
var key = "course['sections']['chapter_index']"
Here I want to get value 5 from data JSON object.
I found the solution to convert "course.sections.chapter_index" to array notation like course['sections']['chapter_index'] this. but don't know how to extract value from data now
<script type="text/javascript">
var BRACKET_REGEXP = /^(.*)((?:\s*\[\s*\d+\s*\]\s*)|(?:\s*\[\s*"(?:[^"\\]|\\.)*"\s*\]\s*)|(?:\s*\[\s*'(?:[^'\\]|\\.)*'\s*\]\s*))(.*)$/;
var APOS_REGEXP = /'/g;
var DOT_REGEXP = /\./g;
var FUNC_REGEXP = /(\([^)]*\))?$/;
var preEval = function (path) {
var m = BRACKET_REGEXP.exec(path);
if (m) {
return (m[1] ? preEval(m[1]) : m[1]) + m[2] + (m[3] ? preEval(m[3]) : m[3]);
} else {
path = path.replace(APOS_REGEXP, '\\\'');
var parts = path.split(DOT_REGEXP);
var preparsed = [parts.shift()]; // first item must be var notation, thus skip
angular.forEach(parts, function (part) {
preparsed.push(part.replace(FUNC_REGEXP, '\']$1'));
});
return preparsed.join('[\'');
}
};
var data = {"course":{"sections":{"chapter_index":5}}};
var obj = preEval('course.sections.chapter_index');
console.log(obj);
</script>
Hope this also help others. I am near to close the solution,but don't know how can I get nested value from JSON.
This may be a good solution too
getDeepnestedValue(object: any, keys: string[]) {
keys.forEach((key: string) => {
object = object[key];
});
return object;
}
var jsonObject = {"address": {"line": {"line1": "","line2": ""}}};
var modelName = "address.line.line1";
var result = getDescendantPropValue(jsonObject, modelName);
function getDescendantPropValue(obj, modelName) {
console.log("modelName " + modelName);
var arr = modelName.split(".");
var val = obj;
for (var i = 0; i < arr.length; i++) {
val = val[arr[i]];
}
console.log("Val values final : " + JSON.stringify(val));
return val;
}
You are trying to combine 'dot notation' and 'bracket notation' to access properties in an object, which is generally not a good idea.
Source: "The Secret Life of Objects"
Here is an alternative.
var stringInput = 'course.sections.chapter_index'
var splitInput = stringInput.split(".")
data[splitInput[1]]][splitInput[2]][splitInput[3]] //5
//OR: Note that if you can construct the right string, you can also do this:
eval("data[splitInput[1]]][splitInput[2]][splitInput[3]]")
Essentially, if you use eval on a string, it'll evaluate a statement.
Now you just need to create the right string! You could use the above method, or tweak your current implementation and simply go
eval("data.course.sections.chapter_index") //5
Source MDN Eval docs.
var data = {
"course": {
"sections": {
"chapter_index": 5
}
}
};
var key = "course['sections']['chapter_index']";
var keys = key.replace(/'|]/g, '').split('[');
for (var i = 0; i < keys.length; i++) {
data = data[keys[i]];
}
console.log(data);
The simplest possible solution that will do what you want:
var data = {"course":{"sections":{"chapter_index":5}}};
var key = "course['sections']['chapter_index']";
with (data) {
var value = eval(key);
}
console.log(value);
//=> 5
Note that you should make sure key comes from a trusted source since it is eval'd.
Using with or eval is considered dangerous, and for a good reason, but this may be one of a few its legitimate use cases.
If you don't want to use eval you can do a one liner reduce:
var data = {"course":{"sections":{"chapter_index":5}}};
var key = "course['sections']['chapter_index']"
key.split(/"|'|\]|\.|\[/).reduce((s,c)=>c===""?s:s&&s[c], data)

How to access name of key in dynamically created json in action script 3

I have a json object coming from my java code as string :
{
"ABC":["ABC","XYZ","pqr"],
"OMG":["ABC","XYZ","pqr"],
"Hello":["ABC","XYZ","pqr"]
}
on decoding it as
myObj : Object = JSON.decode(result);
Now how do I access key names like ABC, OMG, HELLO...??
Try this will help you.
When you want properties in object use for-in loop or you want value use foreach statement.
var obj:Object = {
"ABC":["ABC","XYZ","pqr"],
"OMG":["ABC","XYZ","pqr"],
"Hello":["ABC","XYZ","pqr"]
};
var jsonText:String = JSON.stringify(obj);
var jsonObj:Object = JSON.parse(jsonText);
for(var key:String in jsonObj){
Alert.show("Key is"+key + " value is "+ jsonObj[key]);
}
Your case exactly
var myObj:Object = JSON.decode(result);
for(var key:String in myObj){
Alert.show("Key is"+key + " value is "+ myObj[key]);
}

How to browse keys of an object

I'm looking to get/display the key name of an object in AS3.
I have for example :
var obj:Object = {key:"value"};
Here I try to display "key" (not its value).
The goal is to be able to merge two objects together.
Any idea ?
Thanks !
To get at the keys of an object you need to loop over them:
for (var key:String in obj) {
trace("key:", key, "value:", obj[key]);
}
Thus, merging obj1 and obj2 (with anything from the second overwriting the first) would look like this:
var merged:Object = {};
var key:String = "";
for (key in obj1) {
merged[key] = obj1[key];
}
for (key in obj2) {
merged[key] = obj2[key];
}

find out object item names in as3

let's say you're passing an object to a function
{title:"my title", data:"corresponding data"}
how can I get the function to know what the names of the items/sub-objects are (title and data) without specifying them?
You can use a for loop as follows:
for (var key:String in obj) {
var value:String = obj[key];
trace(key + ": " + value);
}
Or use the introspection API.
The Flex 3 Help page on Performing Object Introspection has a good overview of these.
You can use a for(String in Object) loop like so:
var i:String;
for(i in object)
{
var key:String = i;
var value:Object = object[i];
// do stuff with key/value
}
PS it would make more sense obviously to use key in the loop, my example is done for the sake of demonstration.
Why was this downvoted.. Because I didn't do a function?
function findKeys(obj:Object):Array
{
var ar:Array = [];
var i:String;
for(i in obj)
{
ar.push(i);
}
return ar;
}
var ob:Object = {things:"value", other:5};
trace(findKeys(ob)); // other,things