簡體   English   中英

JQ-為多個嵌套JSON數組返回一個數組

[英]JQ - return one array for multiple nested JSON arrays

我有一個JSON結構,每個消息都有重復的鍵。 我想將這些組合成每條消息一個數組。

[
{
    "id": 1,
    "PolicyItems": [
        {
            "accesses": [
                {
                    "isAllowed": true, 
                    "type": "drop"
                },
                {
                    "isAllowed": true, 
                    "type": "select"
                }
            ], 
            "groups": [], 
            "users": ["admin"]
        }
    ] 
},
{
    "id": 2,
    "PolicyItems": [
        {
            "accesses": [
                {
                    "isAllowed": true, 
                    "type": "drop"
                }
                {
                    "isAllowed": true, 
                    "type": "update"
                }
            ], 
            "groups": [], 
            "users": [
                "admin",
                "admin2"
            ]
        }
    ] 

}]

我有這個:

cat ranger_v2.json | jq -r '[.[] | {"id", "access_type":(.policyItems[].accesses[] | .type)}]'

但這輸出:

[
  {
    "id": 1,
    "access_type": "drop"
  },
  {
    "id": 1,
    "access_type": "select"
  },
  {
    "id": 2,
    "access_type": "drop"
  },
  {
    "id": 2,
    "access_type": "update"
  }
]

但是,我要輸出的是:

  [{
    "id": 1,
    "access_type": ["drop|select"]
  },
  {
    "id": 2,
    "access_type": ["drop|update"]
  }]

有什么想法可以做到嗎? 我有點難過!

值可以是'drop'和'select',但同樣可以是任何值,因此我不想對它們進行硬編碼。

我找到了可以合作的東西。

如果我用[]包裝查詢...

cat ranger_v2.json | jq -r '[.[] | {"id", "access_type":([.policyItems[].accesses[] | .type])}]'

...它產生這種類型的輸出:

[
 {
  "id": 1,
  "access_type": ["drop","select"]
 },
 {
  "id": 2,
  "access_type": ["drop","update"]
}
]

然后,我可以使用以下內容:

(if (."access_type" | length > 0 ) then . else ."access_type" = [""]  end )]

(."access_type" | @tsv)

在我轉換為@csv並使用sed將其替換為管道之前,請先執行以下操作。

@csv' | sed -e "s/[\t]\+/|/g"

這可能不是獲取我所需要的最經濟的方法,但是它對我有用。 (請讓我知道是否有更好的方法。)

cat ranger_v2.json | jq -r '[.[] | {"id", "access_type":([.policyItems[].accesses[] | .type])}] | .[] | [(if (."access_type" | length > 0 ) then . else ."access_type" = [""]  end )] | .[] | [.id, (."access_type" | @tsv)] | @csv'  | sed -e "s/[\t]\+/|/g"

讓我們從您的輸入中觀察一下過濾器開始:

.[]
| {id, access_type: [.PolicyItems[].accesses[].type]}

產生兩個對象:

{
  "id": 1,
  "access_type": [
    "drop",
    "select"
  ]
}
{
  "id": 2,
  "access_type": [
    "drop",
    "update"
  ]
}

現在,調整上述過濾器以產生所需的格式很簡單:

[.[]
 | {id, access_type: [.PolicyItems[].accesses[].type]}
 | .access_type |= [join("|")] ]

或等效地,單線:

map({id, access_type: [[.PolicyItems[].accesses[].type] | join("|")]})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM