我有兩個 JSON 檔案要傳遞給 jq 物件,請檢查以下內容:
創建.json
{
"email_notifications": {
"on_failure": "_"
},
"name": "_",
"schedule": {
"quartz_cron_expression": "_",
"timezone_id": "Europe/Amsterdam",
"pause_status": "_"
}
}
更新.json
{
"job_id": "_",
"new_settings": {
"email_notifications": {
"on_failure": "_"
},
"name": "_",
"schedule": {
"quartz_cron_expression": "_",
"timezone_id": "Europe/Amsterdam",
"pause_status": "_"
}
}
對于 Create.json,我可以使用以下運算式:
TEMPLATE=`cat $FILE | jq
--arg _parent "$PARENT"
--arg _job_name "$JOB_NAME"
' ( . | .name ) |= $_job_name
| ( . | .schedule.pause_status) |= $_parent'
`
對于 Update.json 我需要使用運算式來包含父鍵名:
TEMPLATE=`cat $FILE | jq
--arg _parent "$PARENT"
--arg _job_name "$JOB_NAME"
' ( .["new_settings"] | .name ) |= $_job_name
| ( .["new_settings"] | .schedule.pause_status) |= $_parent'
為了處理這個問題,我在運算式中使用了 if else 并且它完美地作業:( if .job_id? then .["new_settings"] else . end | .name ) |= $_job_name
但我想將初始部分作為引數傳遞,但它不起作用并出現語法錯誤。如何使引數在傳遞時成為運行時運算式的動態:
Filter="." OR Filter=".["new_settings"]"
TEMPLATE=`cat $FILE | jq
--arg filter "$Filter"
--arg _parent "$PARENT"
--arg _job_name "$JOB_NAME"
' ( $filter | .name ) |= $_job_name
| ( $filter | .schedule.pause_status) |= $_parent'
uj5u.com熱心網友回復:
# --arg root_path ""
# --arg root_path "new_settings"
getpath( $root_path | split(".") ) |= (
.name = $_job_name |
.schedule.pause_status = $_parent
)
引數不應該是一段 jq 代碼。接受一段 jq 代碼傳遞給eval. 但jq甚至沒有eval,所以它甚至不是一種選擇。
我們可以使用 JSON 陣列提供路徑。
# --argjson root_path '[]'
# --argjson root_path '["new_settings"]'
getpath($root_path)
但是點分隔的路徑要好得多。
# --arg root_path ""
# --arg root_path "new_settings"
getpath( $root_path | split(".") ) # Supports objects
getpath( $root_path | split(".") | map( tonumber? // . ) ) # Supports objects & arrays
這給了我們這樣的東西:
getpath( $root_path | split(".") ) as $root |
( $root | .name ) |= $_job_name |
( $root | .schedule.pause_status ) |= $_parent
除了使用$root兩次沒有任何意義。
getpath( $root_path | split(".") ) as $root |
$root |= (
.name |= $_job_name |
.schedule.pause_status |= $_parent
)
要不就
getpath( $root_path | split(".") ) |= (
.name |= $_job_name |
.schedule.pause_status |= $_parent
)
=和之間的唯一區別|=是.提供給右側的背景關系 ( )。因此,先前存在的兩個|=可以簡化為=。
getpath( $root_path | split(".") ) |= (
.name = $_job_name |
.schedule.pause_status = $_parent
)
jqplay 上的 演示 jqplay上的Create.json
演示 Update.json
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/341828.html
