简体   繁体   English

jq 解析 json 并生成 json output

[英]jq to parse json and generate json output

I'm working on finding a solution where I need to parse a json file (input.json) and create json file as output (output.json) after removing few lines.我正在寻找一种解决方案,我需要在删除几行后解析 json 文件(input.json)并创建 json 文件作为 output(output.json)。

Only few version will have both value (ubuntu, centos), most of the version will have either ubuntu or centos.只有少数版本会同时具有这两个值(ubuntu,centos),大多数版本将具有 ubuntu 或 centos。

I tried the following command;我尝试了以下命令;

jq '.[]' input.json

it gives the complete list But don't know how to get values under ubuntu and centos.它给出了完整的列表但不知道如何获取 ubuntu 和 centos 下的值。 any guidance will be beneficial.任何指导都是有益的。

input.json输入。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 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"
    }
  }
]

You can use the following JQ command to remove each sourceUrl ;您可以使用以下 JQ 命令删除每个sourceUrl

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

del() docs del()文档


Output: Output:

[
  {
    "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!在线尝试!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM