如何使用 JQ 删除所有嵌套键

Str*_* B. 5 recursion json nested jq npm-shrinkwrap

我想从一个 npm shrinwrap json 文件中删除所有的 resloved。这会导致在其他机器上运行 npm install 时出现问题。

 "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"
    }
Run Code Online (Sandbox Code Playgroud)

如何从所有文件中删除已解析的密钥

我正在使用模式:

jq 'del(.resolved)' file.json
Run Code Online (Sandbox Code Playgroud)

pea*_*eak 5

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)
Run Code Online (Sandbox Code Playgroud)

如果您的 jq 没有walk/1(在 jq 1.5 发布后仅作为内置函数包含在内),则只需在上述行之前添加其定义(可在网络上轻松获得),或者将其包含在您的 ~/.jq 文件中.