Json提取和使用数据(node.js) [英] Json extract and use data (node.js)
问题描述
如何访问这些数据?
这是我的Json:
{
"6a768d67-82fb-4dd9-9433-d83dbd2f1b78": {
"name": "Bahut",
"11": {
"timestamp": 1380044486000,
"value": "false"
}
},
"4f4a65e4-c41b-4038-8f62-76fe69fedf60": {
"name": "Vit",
"11": {
"timestamp": 1380109392000,
"value": "false"
}
},
"a12d22cc-240e-44d6-bc58-fe17dbb2711c": {
"name": "Cuis",
"11": {
"timestamp": 1379883923000,
"value": "false"
}
}
}
我'我试图读取并提取每个条目的id(xxxxxxxx-xxxx -...- xxxxxxxxx)和name然后放入一个数组。
I'm trying to read and extract for each entries the id (xxxxxxxx-xxxx-...-xxxxxxxxx) and the "name" to put then in an array.
但是我无法做到。
尝试:
var nameid = json.'XXXXX-....-XXXX'.name;
或将' - '替换为''
or replace '-' by ''
var nameid = json.XXXXXXXXX.name;
也不起作用。
推荐答案
您需要使用数组样式访问来获取与ID键关联的子对象:
You need to use array-style access to get the subobject associated with the id key:
var nameid = json["a12d22cc-240e-44d6-bc58-fe17dbb2711c"].name; // or ["name"]
// nameid => "Cuis"
这是因为连字符不是点式访问的有效字符(不能在JavaScript中使用它们的变量名。)
This is because hyphens are not a valid character for dot-style access (can't use them in variable names in JavaScript).
为了提取所有的内容,你需要遍历对象,并将它们添加到数组中,如下所示:
In order to extract all of the you will need to loop through the object, and add them to an array, like so:
var arr = [];
for (var id in json) {
arr.push(json[id]["name"]);
}
这将为您提供该JSON对象中所有名称的数组。
Which will give you an array of all the names in that JSON object.
这篇关于Json提取和使用数据(node.js)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!