jq 解析 json 并生成 json 输出

jq to parse json and generate json output

我正在努力寻找一个解决方案,我需要在其中解析 json 文件 (input.json) 并在之后创建 json 文件作为输出 (output.json)删除几行。

只有少数版本会有这两个值(ubuntu,centos),大多数版本会有ubuntu或centos。

我尝试了以下命令;

jq '.[]' input.json

它给出了完整的列表但是不知道如何在ubuntu和centos下获取值。任何指导都会有所帮助。

input.json

[
  {
    "Version": "1.0",
    "ubuntu": {
      "ver": "1.0.0",
      "filename": "1_0_0.log",
      "sourceUrl": "https://example.com/log/1_0_0.log"
    }
  },
  {
    "Version": "1.1",
    "ubuntu": {
      "ver": "1.0.1",
      "filename": "1_0_1.log",
      "sourceUrl": "https://example.com/log/1_0_1.log"
    }
  },
  {
    "Version": "1.4",
    "ubuntu": {
      "ver": "1.0.4",
      "filename": "1_0_4.log",
      "sourceUrl": "https://example.com/log/1_0_4.log"
    },
    "centos": {
      "ver": "1.0.4",
      "filename": "1_0_4.pdf",
      "sourceUrl": "https://example.com/log/1_0_4.pdf"
    }
  }
]

output.json

[
  {
    "Version": "1.0",
    "ubuntu": {
      "ver": "1.0.0",
      "filename": "1_0_0.log"
    }
  },
  {
    "Version": "1.1",
    "ubuntu": {
      "ver": "1.0.1",
      "filename": "1_0_1.log"
    }
  },
  {
    "Version": "1.4",
    "ubuntu": {
      "ver": "1.0.4",
      "filename": "1_0_4.log"
    },
    "centos": {
      "ver": "1.0.14",
      "filename": "1_0_4.pdf"
    }
  }
]

您可以使用以下 JQ 命令删除每个 sourceUrl;

jq 'del(.. | .sourceUrl?)' input.json

del() docs


输出:

[
  {
    "Version": "1.0",
    "ubuntu": {
      "version": "1.0.0",
      "filename": "1_0_0.log"
    }
  },
  {
    "Version": "1.1",
    "ubuntu": {
      "version": "1.0.1",
      "filename": "1_0_1.log"
    }
  },
  {
    "Version": "1.4",
    "ubuntu": {
      "version": "1.0.4",
      "filename": "1_0_4.log"
    },
    "centos": {
      "version": "1.0.4",
      "filename": "1_0_4.pdf"
    }
  }
]

Try it online!