首页 > 解决方案 > 将 JSON 转换为紧凑格式

问题描述

我正在尝试转换以下 json

{ "application" : [
   { "name" : "app1",
     "policies" : [ 
                    { "name" : "pol_1",
                      "orderNumber" : "10"
                    },
                    { "name" : "pol_2",
                      "orderNumber" : "20"
                    }
                ]
   },
   { "name" : "app2",
     "policies" : [ 
                    { "name" : "pol_A",
                      "orderNumber" : "10"
                    },
                    { "name" : "pol_B",
                      "orderNumber" : "20"
                    }
                ]
   }
]
}

到以下

{ "pol_1":"10", "pol_2":"20" }

使用

jq -r ".application[] | select(.name==\"app1\") | .policies[] | {\".name\" : .orderNumber}" 

我能够得到

{
 "pol_1":"10"
}
{ 
 "pol_2":"20" 
}

知道如何合并它们。我错过了什么还是我做错了?

标签: jsonjq

解决方案


你快到了。用于map创建单个数组而不是两个独立对象,然后用于add合并其内容。

jq '.application[]
    | select(.name == "app1")
    | .policies
    | map({ (.name) : .orderNumber } )
    | add' file.json

推荐阅读