繁体   English   中英

如何使用 jq 和 bash 脚本为 .json 模板分配多个值?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM