Home > Enterprise >  Extract JSON including key with jq command
Extract JSON including key with jq command

Time:03-16

HERE is sample json file.

sample.json

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

I want to divide the above JSON file into the following two files. I want to manage the entire configuration file with one JSON, divide the file when necessary and give it to the tool.

apps.json

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

test.json

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

jq .apps sample.json outputs only value.

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

Can you have any idea?

CodePudding user response:

Construct a new object using {x} which is a shorthand for {x: .x}.

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

Demo

And likewise with {test}.

  • Related