Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing a key from parent object with jq

I'm just now playing with JQ, a JSON command line tool. I haven't been able to find a resource that can help me with a relatively simple problem.

The use case is my JSON file has all sorts of extra things I don't need (upwards of 500mb) and if I could kill a specific key's data it reduces it to almost 1mb.

Pretend I have the following JSON:

{
  "pages": {
    "elems": { ... stuff ... }
  },
  "actions": {
    "pages": { ... stuff ... }
  }
}

What sort of command would I run to delete the 1st level pages entire object and key, but retain the lower level pages intact?

Expected Output:

{
  "actions": {
    "pages": { ... stuff ... }
  }
}

I tried running: jq -c 'del(.pages)' myfile.json >outputfile.json But it seemed to destroy all children keys called pages as well, resulting in something like:

{
  "actions": {}
}

Any help would be appreciated.

like image 223
Nicholas Avatar asked Oct 30 '17 20:10

Nicholas


1 Answers

I believe your original attempt should have worked as expected. Here is what I get when I try it:

$ jq 'del(.pages)' myfile.json
{
  "actions": {
    "pages": {
      "stuff": "..."
    }
  }
}

Try it online at jqplay.org

To remove all pages everywhere you would need something like

$ jq 'del(.. | .pages?)' myfile.json
{
  "actions": {}
}

Try it online at jqplay.org

like image 123
jq170727 Avatar answered Sep 18 '22 09:09

jq170727