[英]How do I assign multiple values to a .json template using jq & bash scripting?
我有一個文件,其中包含“name”、“profile”、“os”的值行。 我創建了一個 bash 腳本,它以我想要的格式組織值。 我已經創建了一個模板,其中包含我將使用的其他值(見下文)。 使用 jq(如果可能),如何用新值替換舊值?
文件(ii.json):
Mark,controller-install,installed
Chris,controller-install,installed
模板:
{
"name": "jeff",
"profile": "worker-install",
"selector": {
"mac": "4c:pc:ef:4d:33:29",
"os": "n/a"
}
}
請你試試:
while IFS="," read -r name profile os; do
jq ".name = \"$name\" | .profile = \"$profile\" | .selector.os = \"$os\"" < template.json
done < ii.json
輸出:
{
"name": "Mark",
"profile": "controller-install",
"selector": {
"mac": "4c:pc:ef:4d:33:29",
"os": "installed"
}
}
{
"name": "Chris",
"profile": "controller-install",
"selector": {
"mac": "4c:pc:ef:4d:33:29",
"os": "installed"
}
}
希望它滿足您的要求。
您的模板是您傳入的文件嗎? 或者這只是一般結構? 您可以讀取原始的 (csv) 文件,以逗號分隔,並生成 json。
$ jq -R '
split(",") as [$name, $profile, $os]
| {$name, $profile: selector: {mac: "4c:pc:ef:4d:33:29", $os}}
' input.csv
否則,根據需要加載模板並更新字段。 您可以單獨更新它們或只是合並。
$ jq -R --argfile template template.json '
split(",") as [$name, $profile, $os]
| $template * {$name, $profile, selector: {$os}}
' input.csv
“純jq”解決方案:
jq -R —-argfile template template.json ’
split(",") as [$name,$profile,$os],
| $template
| .name = $name
| .profile = $profile
| .selector.os = $os' ii.json
這假設有一個 bash 或類似 bash 的外殼。 通常,將 jq 程序放入文件並使用 -f 選項調用 jq 可能是可行的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.