【发布时间】:2016-09-28 22:31:39
【问题描述】:
我正在运行一个 node.js 服务器,它将查询发送到一个 elasticsearch 实例。以下是查询返回的 JSON 示例:
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 9290,
"max_score": 0,
"hits": []
},
"suggest": {
"postSuggest": [
{
"text": "a",
"offset": 0,
"length": 1,
"options": [
{
"text": "Academic Librarian",
"score": 2
},
{
"text": "Able Seamen",
"score": 1
},
{
"text": "Academic Dean",
"score": 1
},
{
"text": "Academic Deans-Registrar",
"score": 1
},
{
"text": "Accessory Designer",
"score": 1
}
]
}
]
}
}
我需要创建一个数组,其中包含每个职位的字符串。我遇到了这种我无法弄清楚的奇怪行为。每当我尝试从 JSON 中提取值时,我都无法低于options,否则一切都返回为未定义。
例如:
arr.push(results.suggest.postSuggest) 将推送您所期望的内容:postSuggest 中的所有内容。
arr.push(results.suggest.postSuggest.options) 将显示为未定义,即使在没有.options 的情况下运行它时我可以看到它。对于低于.options 的任何内容也是如此。
我认为这可能是因为.options 是某种作用于变量的内置函数,因此不是将选项视为 JSON,而是尝试在 results.suggest.postSuggest 上运行函数
【问题讨论】:
-
postSuggest是一个数组(括号,[..]),其中包含一个对象(大括号,{..})。您需要先访问数组的索引——postSuggest[0].options。 – Access / process (nested) objects, arrays or JSON -
解决了我的问题,谢谢。我从来没有注册过它是一个数组。
标签: javascript json node.js mongodb elasticsearch