Text-Processing

使用 jq 從 json 文件中檢索值

  • August 22, 2017

如何列印“遊戲”、“玩具”、“書籍”之後的值?這是 jq ‘.’ 的輸出。在文件上:

 {
    "reports": [
        {
          "games": 3,
          "toys": 0,
          "books": 3,
          "to": "2017-07-22T00:00:00.000+0000",
          "from": "2017-07-21T00:00:00.000+0000",
          "eventType": "bookedIn",
          "rowName": "CWQ"
        },
        {
          "games": 0,
          "toys": 0,
          "books": 0,
          "to": "2017-07-22T00:00:00.000+0000",
          "from": "2017-07-21T00:00:00.000+0000",
          "eventType": "bookedOut",
          "rowName": "AED"
        }
    ]
 }

我試過了

{迴聲“

$$ “; cat file; echo " $$”; } | jq -r ’ 。$$ $$| ( “\n” + .rowName + “:”, “games -> " + (.games | tostring), “toys -> " + (.toys | tostring), “books -> " + (.books | tostring ) ) '

看來我做錯了什麼。

更新 據我所知,假設書籍還有另外兩項:提供者和名稱:-?

jq -r '.reports |
.[] |
("\n" + .rowName + ":",
"Games: " + (.games | tostring),
"Toys: " + (.toys | tostring),
.books | .[] |
("\n" + .name + ": ",
"provider: " + (.provider | tostring) ) ) 
' response.json

會得到 jq: error (at response.json:1): Cannot iterate over null (null)

使用 JSON 命令行解析器jq

$ jq -r '.reports[] |          
        "\(.rowName) :",     
        "books -> \(.books)",
        "toys -> \(.toys)",  
        "games -> \(.games)\n"' input.json

CWQ:
books -> 3
toys -> 0
games -> 3

AED:
books -> 0
toys -> 0
games -> 0

注意:這使用jq’ 字元串插值並遍歷reports數組中的所有條目,挑選出相關資訊。


更新:處理.books對像數組:

給定

{
 "reports": [
   {
     "games": 3,
     "toys": 0,
     "books": [
       {
         "provider": "The provider",
         "name": "The name"
       }
     ],
     "to": "2017-07-22T00:00:00.000+0000",
     "from": "2017-07-21T00:00:00.000+0000",
     "eventType": "bookedIn",
     "rowName": "CWQ"
   },
   {
     "games": 0,
     "toys": 0,
     "books": [
       {
         "provider": "The 1st provider",
         "name": "The 1st name"
       },
       {
         "provider": "The 2nd provider",
         "name": "The 2nd name"
       }
     ],
     "to": "2017-07-22T00:00:00.000+0000",
     "from": "2017-07-21T00:00:00.000+0000",
     "eventType": "bookedOut",
     "rowName": "AED"
   }
 ]
}

我們可以簡單地做

$ jq -r '.reports[] |
        "\(.rowName):",
        ( .books[] | "book name -> \(.name)",
                     "book provider -> \(.provider)" ),
        "toys -> \(.toys)",
        "games -> \(.games)\n"'

CWQ:
book name -> The name
book provider -> The provider
toys -> 0
games -> 3

AED:
book name -> The 1st name
book provider -> The 1st provider
book name -> The 2nd name
book provider -> The 2nd provider
toys -> 0
games -> 0

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