首页 > 解决方案 > 使用 JQ 将字段名称提取到新对象中

问题描述

Spring 在 env-endpoint 提供有关环境的信息。我想简化输出,看起来像这样:

{
  "propertySources": [
    {
      "name": "ports",
      "properties": {
        "server.port": {
          "value": 9110
        },
        "management.port": {
          "value": 9350
        }
      }
    },
    {
      "name": "trees",
      "properties": {
        "oak": {
          "value": "true"
        }
      }
    },
    {
      "name": "elephants",
      "properties": {}
    },
    ...
}

我只想将键值对视为输出,如下所示:

{
  "server.port": 9110,
  "management.port": 9350,  
  "oak": "true",
  ...
}

使用 JQ 我尝试了一些从

curl https://localhost:9350/actuator/env/ -s | jq '[.propertySources[].properties[]]'

并尝试mapselect并且with_entries,但我无法让它运行。你能给我一个正确的方向吗?

标签: jsonjq

解决方案


您可以简单地添加properties对象,但为了获得该输出作为回报,您也需要取出value字段。

.propertySources | map(.properties) | add | map_values(.value)

在线演示


推荐阅读