Json

jq過濾器:顯示帶有選擇的整個結構

  • July 12, 2021

我有以下file1 json:

{
 "name": "eye",
 "attributes": [
   {
     "name": "Width",
     "value": "1920"
   },
   {
     "name": "Height",
     "value": "1080"
   },
   {
     "name": "WinKeyMapping",
     "value": "leftwin"
   }
 ],
 "starts": [
   {
     "name": "step1",
     "attributeList": [
       {
         "name": "Command",
         "value": "bash"
       },
       {
         "name": "Test",
         "value": "none"
       }
     ]
   }
 ]
}

和以下過濾器:

$ jq '.starts[].attributeList[]|select(.name=="Command")' file1
{
 "name": "Command",
 "value": "bash"
}
$

我怎樣才能得到這個選擇的整個結構?

預期輸出:

{
 "starts": [
   {
     "attributeList": [
       {
         "name": "Command",
         "value": "bash"
       }
     ]
   }
 ]
}

直截了當**jq**:

jq '{ starts: [ { attributeList: (.starts[].attributeList 
                                 | map(select(.name == "Command"))) }] }' file.json

輸出:

{
 "starts": [
   {
     "attributeList": [
       {
         "name": "Command",
         "value": "bash"
       }
     ]
   }
 ]
}

以下是獲得所需輸出的兩個選項。

您可以刪除不需要的密鑰:

jq 'del(.attributes, .name) | 
 .starts[].attributeList = map(.[].attributeList[] | select(.name == "Command"))'

或者您可以只選擇您想要的鍵:

jq 'to_entries | map(select(.key == "starts")) | from_entries | 
 .starts[].attributeList = map(.[].attributeList[] | select(.name == "Command"))'

兩者都給出相同的結果。此外,如果您願意starts並且ends在後一種情況下,您可以添加額外的or語句:map(select((.key == "starts") or (.key == "ends"))).

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