2017-08-05 32 views
0

我分析有JQ JSON文件:得到一個數組中所有的值與JQ

jq .response[1].text file.json 

它工作正常,但每次我都進入.response [2]的.text數量,.response [3]的.text等。我想在一次(200個值)

把所有的值,但,當我做:

jq .response[].text file.json 

它給出了一個錯誤:無法索引號與字符串「文本」

文件看起來是這樣的:

{ 
 
    "response": [ 
 
    1000, 
 
    { 
 
     "id": , 
 
     "date": , 
 
     "owner_id": , 
 
     "from_id": , 
 
     "post_type": "post", 
 
     "text": "blabla", 
 
     "attachment": { 
 
     "type": "photo", 
 
     "photo": { 
 
      "pid": , 
 
      "aid": -7, 
 
      "owner_id": 
 
     } 
 
     }, 
 
     "attachments": [ 
 
     { 
 
      "type": "photo", 
 
      "photo": { 
 
      } 
 
     }, 
 
     { 
 
      "type": "link", 
 
      "link": { 
 
      "url": "", 
 
      "title": "", 
 
      "description": "", 
 
      "target": "external" 
 
      } 
 
     } 
 
     ], 
 
     "post_source": { 
 
     "type": "vk" 
 
     }, 
 
     "comments": { 
 
     "count": 0, 
 
     "groups_can_post": true, 
 
     "can_post": 1 
 
     }, 
 
    }, 
 
    { 
 
     "id": , 
 
     "date": , 
 
     "owner_id": , 
 
     "from_id": , 
 
     "post_type": "post", 
 
     "text": "blabla", 
 
     "attachment": { 
 
     "type": "link", 
 
     "link": { 
 
      "url": "", 
 
      "title": "", 
 
      "description": "", 
 
      "target": "external", 
 
      " 
 
     }

+0

你能提供一個'file.json'看起來像什麼的簡單例子嗎?另外,你有什麼版本的'jq'?我不能用'jq' 1.5重現錯誤,我假設它是'file.json'的一個例子。 – chepner

+0

我加了上面的例子。我的jq版本是1.5。 –

+0

'響應[0]'不是一個對象;這是一個數字。 – chepner

回答

2

顯然數組中的項目之一是一個字符串。 「?」 如果你的JQ支持,那麼一種可能是使用它:

.response[].text? 

另一個辦法是明確檢查的類型,例如:

.response[] | objects | .text 

另一種可能性:

.response[] | select(type=="object" and has("text")) | .text 

如果要在沒有「文本」字段時佔有一個佔位符值:

.response[] | if type=="object" and has("text") then .text else null end 

所以它真的取決於你的要求,也許你正在使用的jq版本。

+0

非常感謝!))).response [] .text?做了這份工作。 –

相關問題