我有以下JSON我从我的数据库发回,我正在尝试访问'名称'和'联系人的密钥:
[
{
"key": {
"name": "a",
"kind": "Users",
"path": [
"Users",
"a"
]
},
"data": {
"fullname": "a",
"password": "a",
"contacts": [
"bob", "john"
]
}
},
{
"key": {
"name": "b",
"kind": "Users",
"path": [
"Users",
"b"
]
},
"data": {
"fullname": "b",
"password": "b",
"contacts": [
"john"
]
}
}
]
我的java脚本回调函数看起来像这样,在里面我试图打印来自实体变量的值:
dataset.get(keys, function(err, entities) {});
我试过:entities.key.name[0]
获取名字的第一个键值,但它不起作用。我也被困在如何获取联系人变量。
答案 0 :(得分:1)
使用控制台查看内容:
var entities = [
{
"key": {
"name": "a",
"kind": "Users",
"path": [
"Users",
"a"
]
},
"data": {
"fullname": "a",
"password": "a",
"contacts": [
"bob", "john"
]
}
},
{
"key": {
"name": "b",
"kind": "Users",
"path": [
"Users",
"b"
]
},
"data": {
"fullname": "b",
"password": "b",
"contacts": [
"john"
]
}
}
];
console.log(entities);
console.log(entities[1].key.name);
console.log(entities[1].data.contacts[0]);
答案 1 :(得分:1)
如果将此JSON对象分配到的变量为entities
然后
entities[ 0 ][ "key" ].name; //will give you name
entities[ 0 ][ "data" ].contacts; //will give you contacts
现在您可以将entities
重复为
entities[ counter ][ "key" ].name; //will give you name
entities[ counter ][ "data" ].contacts; //will give you contacts
答案 2 :(得分:1)
你有一个阵列。所以你必须使用索引从中读取一个项目。
entities[0]
返回第一个对象。
{
"key": {
"name": "a",
"kind": "Users",
"path": [
"Users",
"a"
]
},
"data": {
"fullname": "a",
"password": "a",
"contacts": [
"bob", "john"
]
}
}
您可以使用点表示法或括号表示法来读取对象的值。例如,如果您想阅读密钥,请尝试以下方法:
entities[0].key
现在key
引用了以下对象:
{
"name": "a",
"kind": "Users",
"path": [
"Users",
"a"
]
}
所以,如果你想获得name
,只需再做一步:
entities[0].key.name
同样适用于contacts
:
entities[0].data.contacts
答案 3 :(得分:1)
使用entities[ 0 ][ "key" ].name;
作为实体是array
答案 4 :(得分:1)
您可以尝试这样的事情:
var json = [{
"key": {
"name": "a",
"kind": "Users",
"path": [
"Users",
"a"
]
},
"data": {
"fullname": "a",
"password": "a",
"contacts": [
"bob", "john"
]
}
}, {
"key": {
"name": "b",
"kind": "Users",
"path": [
"Users",
"b"
]
},
"data": {
"fullname": "b",
"password": "b",
"contacts": [
"john"
]
}
}]
function getJSONValues(){
var names = [], contacts = [];
for (var obj in json){
console.log(json[obj]);
names.push(json[obj].key.name);
contacts.push(json[obj].data.contacts.splice(0));
}
console.log(names, contacts)
}
getJSONValues();