我花了最后几个小时试图弄清楚这一点。 我使用 JQuery 发出 ajax 请求。我收到字符串格式的响应,我使用
jQuery.parseJSON(response);
将其转换为对象。 这是我的回复:
{
"columns": ["n"],
"data": [
[{
"extensions": {},
"labels": "http://localhost:7474/db/data/node/168/labels",
"outgoing_relationships": "http://localhost:7474/db/data/node/168/relationships/out",
"traverse": "http://localhost:7474/db/data/node/168/traverse/{returnType}",
"all_typed_relationships": "http://localhost:7474/db/data/node/168/relationships/all/{-list|&|types}",
"property": "http://localhost:7474/db/data/node/168/properties/{key}",
"self": "http://localhost:7474/db/data/node/168",
"properties": "http://localhost:7474/db/data/node/168/properties",
"outgoing_typed_relationships": "http://localhost:7474/db/data/node/168/relationships/out/{-list|&|types}",
"incoming_relationships": "http://localhost:7474/db/data/node/168/relationships/in",
"create_relationship": "http://localhost:7474/db/data/node/168/relationships",
"paged_traverse": "http://localhost:7474/db/data/node/168/paged/traverse/{returnType}{?pageSize,leaseTime}",
"all_relationships": "http://localhost:7474/db/data/node/168/relationships/all",
"incoming_typed_relationships": "http://localhost:7474/db/data/node/168/relationships/in/{-list|&|types}",
"metadata": {
"id": 168,
"labels": []
},
"data": {
"name": "1"
}
}]
]
}
我尝试访问此对象的特定元素,但没有得到任何回复。当我尝试这个时
var test = json.data;
它有效,但我如何访问元数据中保存的值。 我试试这个,但我得到“未定义”:
var test = json.data.metadata.id;
知道我错过了什么吗?
最佳答案
它是一个数组,所以你必须使用索引
var test = json.data[0][0].metadata.id;
json.data[0]
返回 [{...}]
并再次返回 [{...}][0]
返回具有 metadata
对象的 {...}
,而后者又是您需要的 id
属性。
关于javascript - ajax 请求后访问 JSON 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27505740/