【问题标题】:Using `jq` to add key/value to a json file using another json file as a source使用 `jq` 将键/值添加到使用另一个 json 文件作为源的 json 文件中
【发布时间】:2021-01-17 14:53:04
【问题描述】:

已经为此苦苦挣扎了一段时间,但我离解决方案还差得远。我对使用jq 不是很有经验。

当 dict 中的其他值匹配时,我想从一个 json 文件中获取值并将它们添加到另一个文件中。下面的示例文件比解释更清楚地展示了我想要什么。

hosts.json:

{
  "hosts": [
    {
      "host": "hosta.example.com",
      "hostid": "101",
      "proxy_hostid": "1"
    },
    {
      "host": "hostb.example.com",
      "hostid": "102",
      "proxy_hostid": "1"
    },
    {
      "host": "hostc.example.com",
      "hostid": "103",
      "proxy_hostid": "2"
    }
  ]
}

proxies.json:

{
  "proxies": [
    {
      "host": "proxy1.example.com",
      "proxyid": "1"
    },
    {
      "host": "proxy2.example.com",
      "proxyid": "2"
    }
  ]
}

我还可以使用 proxyid 作为密钥的上述文件,如果这样更容易的话:

{
  "proxies": {
    "1": {
      "host": "proxy1.example.com",
      "proxyid": "1"
    },
    "2": {
      "host": "proxy2.example.com",
      "proxyid": "2"
    }
  }
}

使用上面的这些json文件(来自Zabbix API),我想将.proxies[].host(来自proxies.json)的值添加为.hosts[].proxy_host(到hosts.json)。

这只会在.hosts[].proxy_hostid 等于.proxies[].proxyid 时发生

期望的输出:

{
  "hosts": [
    {
      "host": "hosta.example.com",
      "hostid": "101",
      "proxy_hostid": "1",
      "proxy_host": "proxy1.example.com"
    },
    {
      "host": "hostb.example.com",
      "hostid": "102",
      "proxy_hostid": "1",
      "proxy_host": "proxy1.example.com"
    },
    {
      "host": "hostc.example.com",
      "hostid": "103",
      "proxy_hostid": "2",
      "proxy_host": "proxy2.example.com"
    }
  ]
}

我尝试了很多不同的方法,并且认为我需要使用jq -s 或jq --slurpfile,但我已经走到了很多死胡同,找不到解决方案。

jq 'input as $p | map(.[].proxy_host = $p.proxies[].proxyid)' hosts.json proxies.json

我想我也需要这样的东西,但不知道如何使用它。

if .hosts[].proxy_hostid == .proxies[].proxyid then .hosts[].proxy_host = .proxies[].host else empty end'

我找到了这些问题,但没有帮助:(

【问题讨论】:

    标签: json jq


    【解决方案1】:

    使用proxies.json 的替代版本确实更容易。您只需将代理存储在变量中作为参考,并在更新主机时从中检索代理主机。

    jq 'input as { $proxies } | .hosts[] |= . + { proxy_host: $proxies[.proxy_hostid].host }' hosts.json proxies.json
    

    Online demo

    【讨论】:

      猜你喜欢
      • 2020-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-26
      相关资源
      最近更新 更多