![](/img/trans.png)
[英]How to merge JSON objects with sub arrays with adding objects with matching values inside the array instead of replacing them with jq?
[英]How to merge different objects and arrays in the same json file using jq
我有一個包含以下內容的 json 文件
{
"Cities":
{
"city": New York,
"zip_code": "10034",
"state": "NY"
},
"addresss": [
{
"address_line1": 123 Main Street,
"address_line2": Unit 130
},
{
"address_line1": 5th Avenue,
"address_line2": East River Tower
}
]
}
我正在嘗試組合這兩個對象( Cities 和數組地址)並創建一個新數組 mailing_address ,如下所示
mailing_address:[
{
"address_line1": 123 Main Street,
"address_line2": Unit 130,
"city": New York,
"zip_code": "10034",
"state": "NY"
},
{
"address_line1": 5th Avenue,
"address_line2": East River Tower,
"city": New York,
"zip_code": "10034",
"state": "NY"
}
]
我嘗試過添加、映射和減少,但是所有這些方法都只將城市添加到第一個元素而不是每個元素。 有沒有辦法使用 jq 執行此操作?
謝謝
.Cities as $c | { mailing_address: (.addresss | map(. * $c)) }
將輸出:
{
"mailing_address": [
{
"address_line1": "123 Main Street",
"address_line2": "Unit 130",
"city": "New York",
"zip_code": "10034",
"state": "NY"
},
{
"address_line1": "5th Avenue",
"address_line2": "East River Tower",
"city": "New York",
"zip_code": "10034",
"state": "NY"
}
]
}
首先,我們將 Cities 對象保存到一個變量中。 然后我們使用您的mailing_address
鍵創建一個新對象,遍歷每個地址並向其添加 (*) Cities 變量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.