简体   繁体   中英

How do I assign multiple values to a .json template using jq & bash scripting?

I have a file that contains lines of values for "name", "profile", "os". I have created a bash script that organizes the values in a format I want. I have a template already created with other values that I will use (see below). Using jq (if possible), how can I replace the old values with the new ones?

File (ii.json):

Mark,controller-install,installed
Chris,controller-install,installed

TEPMLATE:

{
  "name": "jeff",
  "profile": "worker-install",
  "selector": {
    "mac": "4c:pc:ef:4d:33:29",
    "os": "n/a"
  }
}

Would you please try:

while IFS="," read -r name profile os; do
    jq ".name = \"$name\" | .profile = \"$profile\" | .selector.os = \"$os\"" < template.json
done < ii.json

Output:

{
  "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"
  }
}

Hope it meets your requirement.

Is your template a file that you're passing in? Or is that just the general structure? You can read the (csv) file raw, split on commas, and generate the json.

$ jq -R '
split(",") as [$name, $profile, $os]
  | {$name, $profile: selector: {mac: "4c:pc:ef:4d:33:29", $os}}
' input.csv

Otherwise, load the template and update the fields as necessary. You could update them individually or just merge.

$ jq -R --argfile template template.json '
split(",") as [$name, $profile, $os]
  | $template * {$name, $profile, selector: {$os}}
' input.csv

A “pure jq” solution:

    jq -R —-argfile template template.json ’
      split(",") as [$name,$profile,$os],
      | $template
      | .name = $name 
      | .profile = $profile
      | .selector.os = $os' ii.json

This assumes a bash or bash-like shell. In general, putting the jq program into a file and invoking jq with the -f option, might be the way to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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