How to delete all nested keys with JQ
Asked Answered
A

1

8

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
Auriga answered 1/11, 2016 at 13:51 Comment(0)
C
10

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.

Copse answered 1/11, 2016 at 14:42 Comment(5)
In jq terminology, it's a filter, just like the one you provided. You can give it on the command line as you did, or put it in a file and invoke jq with the -f option.Copse
How to add WALK ?Auriga
Until 1.6's release, you can download and install it from source github.com/stedolan/jq/tree/jq-1.6rc1 and install is by following the instructions in the READMEDougie
The simplest way to make walk available is to include its def in your program. See github.com/stedolan/jq/wiki/FAQ for its def and further details. The def can also be obtained from raw.githubusercontent.com/stedolan/jq/master/src/builtin.jqCopse
Note that the has("resolved") is unnecessary. It seems like jq will just try to delete and if it can't nothing bad will happen. Might come in handy if you need to delete more than a few thingsMandarin

© 2022 - 2024 — McMap. All rights reserved.