2016-05-31 29 views
0

我正在運行一個node.js服務器,它將查詢發送到elasticsearch實例。下面是查詢返回的JSON的一個示例:elasticsearch autosuggest返回棘手的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

+2

'postSuggest'是一個數組(括號'[ ..]')包含一個對象(大括號,'{..}')。您需要首先訪問數組的索引 - 'postSuggest [0] .options'。 - [訪問/進程(嵌套)對象,數組或JSON](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) –

+0

解決了我的問題,謝謝。我從來沒有註冊過它是一個數組。 – IanCZane

回答

1

arr.push運行功能(results.suggest.postSuggest.options)

postSuggest是一個對象數組。 options裏面的postSuggest也是對象的數組。因此,首先你需要postSuggest[0]得到postSuggest然後 postSuggest[0].options得到的options

陣列下面這個片段可以usefule

var myObj = {..} 
// used jquery just to demonstrate postSuggest is an Array 
console.log($.isArray(myObj.suggest.postSuggest)) //return true 
var getPostSuggest =myObj.suggest.postSuggest //Array of object 
var getOptions = getPostSuggest[0].options; // 0 since it contain only one element 
console.log(getOptions.length) ; // 5 , contain 5 objects 
getOptions.forEach(function(item){ 
    document.write("<pre>Score is "+ item.score + " Text</pre>") 
}) 

Jsfiddle