Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete all nested keys with JQ

I would like to delete all the resloved from a npm shrinwrap json file. this is causing a problem when running npm install on other machine.

 "cssstyle": {
      "version": "0.2.37",
      "from": "cssstyle@>=0.2.29 <0.3.0",
      "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-0.2.37.tgz"
    },
    "dashdash": {
      "version": "1.14.0",
      "from": "dashdash@>=1.12.0 <2.0.0",
      "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.0.tgz",
      "dependencies": {
        "assert-plus": {
          "version": "1.0.0",
          "from": "assert-plus@>=1.0.0 <2.0.0",
          "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz"
        }
      }
    },
    "debug": {
      "version": "2.2.0",
      "from": "debug@>=2.2.0 <3.0.0",
      "resolved": "https://registry.npmjs.org/debug/-/debug-2.2.0.tgz"
    }

How can I delete the resolved key from all the file

I'm using the pattern :

jq 'del(.resolved)' file.json
like image 568
Stranger B. Avatar asked Nov 01 '16 13:11

Stranger B.


1 Answers

In my opinion, the simplest approach to this kind of problem is to use walk/1:

walk(if type == "object" and has("resolved") then del(.resolved) else . end)

If your jq does not have walk/1 (which was only included as a builtin after the release of jq 1.5), then simply add its definition (easily available on the web) before the above line, or perhaps include it in your ~/.jq file.

like image 62
peak Avatar answered Oct 12 '22 20:10

peak