在一次调用中更新多个路径

wil*_*mdh 1 bash json jq

有没有办法在 Bash 中使用 jq 一次更新 json 文件中的多个值?例如:

#!/bin/bash

explore_host_name () {
  host_name_lastrun=$(date '+%Y-%m-%d %H:%M:%S,%3N')
  host_name_value="$(hostname)"
  result=$(jq --arg host_name_value "$host_name_value" '.host.properties.name.value = $host_name_value' data/firemotd-data-host.json)
  echo "${result}" > data/firemotd-data-host.json
  result=$(jq --arg host_name_lastrun "$host_name_lastrun" '.host.properties.name.lastrun = $host_name_lastrun' data/firemotd-data-host.json)
  echo "${result}" > data/firemotd-data-host.json
}

explore_host_name
Run Code Online (Sandbox Code Playgroud)

json文件:

{
  "host": {
    "properties": {
      "name": {
        "generated": "@logon",
        "value": "${host.name}",
        "lastrun": "2020-06-09 20:48:00,357",
        "type": "keyword"
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

理想我想更新host.properties.name.lastrun,并host.properties.name.value在同一时间。

ogu*_*ail 6

在 JQ 中,您可以将赋值的结果通过管道传递给另一个。例如:

jq --arg host_name_value   "$host_name_value"   \
   --arg host_name_lastrun "$host_name_lastrun" '
.host.properties.name |= (
  .value   = $host_name_value   |
  .lastrun = $host_name_lastrun
)' data/firemotd-data-host.json
Run Code Online (Sandbox Code Playgroud)