[英]How to insert a key-value pair after a specified key in a JSON object using jq?
我有一個像這樣的JSON文件
{
"hierarchy": {
"structure": {
"card_11001": [
"addCard_4111"
],
"container_11006": [
"mainContainer_11007",
"subContainer_10016"
],
"mainContainer_11007": [
"paymentMethodList_10001"
],
"orderWrap_10012": [
"orderSummary_10005"
],
"paymentMethodList_10001": [
"card_11001",
"placeOrder_10013"
],
"root_10000": [
"payNotice_11011",
"payNotice_10020",
"container_11006",
"placeOrderResultAction_10004"
],
"subContainer_10016": [
"orderWrap_10012",
"footer_10014"
]
}
}
}
我想插入
"offline_11018": [
"instruction_908",
"checkboxList_11019"
]
在"mainContainer_11007"
和"orderWrap_10012"
,因此我想要的結果應如下所示:
{
"hierarchy": {
"structure": {
"card_11001": [
"addCard_4111"
],
"container_11006": [
"mainContainer_11007",
"subContainer_10016"
],
"mainContainer_11007": [
"paymentMethodList_10001"
],
"offline_11018": [
"instruction_908",
"checkboxList_11019"
],
"orderWrap_10012": [
"orderSummary_10005"
],
"paymentMethodList_10001": [
"card_11001",
"placeOrder_10013"
],
"root_10000": [
"payNotice_11011",
"payNotice_10020",
"container_11006",
"placeOrderResultAction_10004"
],
"subContainer_10016": [
"orderWrap_10012",
"footer_10014"
]
}
}
}
我所知道的是,我只能將其附加到文件末尾
jq --raw-output '.hierarchy.structure + {"offline_11018": ["instruction_908","checkboxList_11019"]}'
但這不是我想要的,我想在其他兩個鍵之間插入它。 我該如何使用jq命令?
最簡單的方法是使用to_entries
將.hierarchy.structure
轉換為數組,執行插入,然后使用from_entries
來重構對象,方法如下:
.hierarchy.structure |= (to_entries
| ... as $ix
| .[:$ix] + ($x | to_entries) + .[$ix:]
| from_entries)
如果可能找不到定義插入點的項目,則當然需要修改以上草圖。
indexof/1
這是一個有用的“ def”,用於查找滿足某些條件的最小索引:
# If the input is an array, emit the least index, $i,
# for which `.[$i]|f` is truthy, otherwise emit null.
# Works similarly if the input is a JSON object.
def indexof(f):
label $out
| foreach .[] as $x (null; .+1;
if ($x|f) then (.-1, break $out) else empty end) // null;
indexof
解決方案 將以上各部分放在一起:
{"offline_11018": [ "instruction_908", "checkboxList_11019" ]} as $x
| .hierarchy.structure |= (to_entries
| (1 + indexof( .value | index("mainContainer_11007") )) as $ix
| .[:$ix] + ($x | to_entries) + .[$ix:]
| from_entries)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.