从 JSON 获取元素集合
Get collection of elements from JSON
我有一个 JSON 文件,其结构如下:
{"root" : {
"parent" : {
"childA" :
["element1",
"element2"],
"childB" :
["element1",
"element2"]
}
}
我怎样才能从中得到子集[childA, childB]
?
目前我在做什么:
将 JSON 文件解析为一个对象(我知道该怎么做,建议的回复是关于这个的)。
创建集合:
var collection = [JSON.root.parent.childA, JSON.root.parent.childB];
collection.forEach(function(child) {
print(child[0])
});
打印"element1"
。
我是 JavaScript 的新手,但我相信有更好、更通用的方法来实现第 2 点。
编辑:
我忘了补充一点,这个 Java 脚本是在 Nashorn jjs 脚本中使用的。
只需使用 Object.keys()
即可:
var data = {"root" : {
"parent" : {
"childA" :
["element1",
"element2"],
"childB" :
["element1",
"element2"]
}
}
};
var collection = [];
for (var childIndex in data.root.parent){
data.root.parent[childIndex].every(child => collection.push(child));
};
console.log(collection);
您可以使用 Object.values
获取父对象中的条目。
var data = {"root" : {
"parent" : {
"childA" :
["element1",
"element2"],
"childB" :
["element1",
"element2"]
}
}
};
var collection = [];
for (var o in data.root.parent){
collection.push(data.root.parent[o]);
}
collection.forEach(function(child) {
console.log(child[0]);
});
您也可以尝试使用 JToken -
using Newtonsoft.Json.Linq;
JToken.Parse(response.Content)
.SelectTokens("root.parent");
我有一个 JSON 文件,其结构如下:
{"root" : {
"parent" : {
"childA" :
["element1",
"element2"],
"childB" :
["element1",
"element2"]
}
}
我怎样才能从中得到子集[childA, childB]
?
目前我在做什么:
将 JSON 文件解析为一个对象(我知道该怎么做,建议的回复是关于这个的)。
创建集合:
var collection = [JSON.root.parent.childA, JSON.root.parent.childB]; collection.forEach(function(child) { print(child[0]) });
打印"element1"
。
我是 JavaScript 的新手,但我相信有更好、更通用的方法来实现第 2 点。
编辑: 我忘了补充一点,这个 Java 脚本是在 Nashorn jjs 脚本中使用的。
只需使用 Object.keys()
即可:
var data = {"root" : {
"parent" : {
"childA" :
["element1",
"element2"],
"childB" :
["element1",
"element2"]
}
}
};
var collection = [];
for (var childIndex in data.root.parent){
data.root.parent[childIndex].every(child => collection.push(child));
};
console.log(collection);
您可以使用 Object.values
获取父对象中的条目。
var data = {"root" : {
"parent" : {
"childA" :
["element1",
"element2"],
"childB" :
["element1",
"element2"]
}
}
};
var collection = [];
for (var o in data.root.parent){
collection.push(data.root.parent[o]);
}
collection.forEach(function(child) {
console.log(child[0]);
});
您也可以尝试使用 JToken -
using Newtonsoft.Json.Linq;
JToken.Parse(response.Content)
.SelectTokens("root.parent");