Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

apps.json

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

test.json

// Not contain the key
{
  "test": [
    {
      "name": "test1"
    },
    {
      "name": "test1"
    }
  ]
}

jq .apps sample.json outputs only value.

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

Can you have any idea?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading