使用 jq 命令提取 JSON 包括密钥

Extract JSON including key with jq command

这里是示例 json 文件。

sample.json

{
  "apps": [
    {
      "name": "app1"
    },
    {
      "name": "app2"
    },
    {
      "name": "app3"
    }
  ],
  "test": [
    {
      "name": "test1"
    },
    {
      "name": "test2"
    }
  ]
}

我想把上面的JSON文件分成下面两个文件。 我想用一个JSON管理整个配置文件,需要的时候分文件交给工具

apps.json

{
  "apps": [
    {
      "name": "app1"
    },
    {
      "name": "app2"
    },
    {
      "name": "app3"
    }
}

test.json

{
  "test": [
    {
      "name": "test1"
    },
    {
      "name": "test1"
    }
  ]
}

jq .apps sample.json 只输出值。

[
// Not contain the key
  {
    "name": "app1"
  },
  {
    "name": "app2"
  },
  {
    "name": "app3"
  }
]

你有什么想法吗?

Construct 使用 {x} 的新对象,它是 {x: .x} 的 shorthand。

jq '{apps}' sample.json
{
  "apps": [
    {
      "name": "app1"
    },
    {
      "name": "app2"
    },
    {
      "name": "app3"
    }
  ]
}

Demo

{test}.

也是如此

你可以做到

{apps}, {test}

演示

https://jqplay.org/s/P_9cc2uANV