Jq

使用 jq 解析 JSON 數據時出現錯誤消息“Cannot index array with string ‘Title’”

  • March 17, 2019
{
   "content": [
   {
       "Title": "abc",
       "brand": "xyz",
       "size": "5 g",
       "date": "2019-01-01",
       "details": {
           "Temperature": [
           {
               "value": "90",
               "characteristics":"Normal"
           },
           {
               "value":"100",
               "characteristics":"high"
           },

           {
               "value":"80",
               "characteristics":"low"
           }
           ],

           "certifications": [
           {
               "value": "based",
               "characteristics":"pass"
           },

           {
               "value": "50",
               "characteristics":"failed"
           }
           ]
       },

        "formats": {
           "city": "NYC",
           "id": "007",
           "manufacture":""
           },
       "innerDetails": [
       {
           "contains": "abc",
           "panel":"xyz",
           "values":[
               {
                   "name":"abc",
                   "value":"10"
               },
               {
                   "name":"xyz",
                   "value":"20"
               }
               ]
           }
       ]
}
]
}

我嘗試了以下方法,但收到錯誤

無法使用字元串“Title”索引數組

jq -r '.content[]|[.Title,.brand,.characteristics,.value]' $jsonfile.

我試圖與其他部分在同一行,但得到相同的錯誤。

我該如何解決這個問題?

預期輸出:

abc,xyz,90,Normal.
abc,xyz,100,high.
abc,xyz,80,low

你沒有得到Cannot index array with string "Title"那個命令,你得到

[
 "abc",
 "xyz",
 null,
 null
]

因為數組的對像中沒有characteristicsorvaluecontents(它們是.details.Temperature子數組中的鍵)。

會給您該消息的命令是:

jq -r '.[] | [.Title,.brand,.characteristics,.value]' "$jsonfile"

或者

jq -r '.content | [.Title,.brand,.characteristics,.value]' "$jsonfile"

錯過content鍵查找,或者無法獲取數組的元素,會content生成一個包含一個對象的數組,而不是對象本身。而且你不能用字元串索引一個數組。


假設您想要 CSV 輸出:

$ jq -r '.content[] | .details.Temperature[] as $t | [.Title,.brand,$t.value,$t.characteristics] | @csv' file.json
"abc","xyz","90","Normal"
"abc","xyz","100","high"
"abc","xyz","80","low"

<object(s)> as <variable>行為就像一個循環 in jq,所以這裡發生的事情是依次$t分配 的每個元素,並為每個元素構造一個新數組。.details.Temperature[]數組通過@csv它將輸出 CSV 格式的行。

jq將始終雙引號其 CSV 輸出的欄位。擺脫不必要的引號:

jq -r '...as above...' file.json | csvformat

csvformat是一部分csvkit

或者,您可能希望使用@tsv代替@csv來獲得製表符分隔的輸出。

引用自:https://unix.stackexchange.com/questions/506789