mentai
mentai

Reputation: 113

Extract JSON including key with jq command

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?

Upvotes: 1

Views: 72

Answers (2)

Logan Lee
Logan Lee

Reputation: 997

You can do

{apps}, {test}

Demo

https://jqplay.org/s/P_9cc2uANV

Upvotes: 0

pmf
pmf

Reputation: 36391

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}.

Upvotes: 2

Related Questions