【问题标题】:How to fetch values of json file using shell script?如何使用 shell 脚本获取 json 文件的值?
【发布时间】:2022-12-05 20:49:47
【问题描述】:

我有一个示例 json 文件,如下所示:

 {
  "component": {
    "id": "xxxxxxxx",
    "key": "abc",
    "name": "project",
    "qualifier": "TRK",
    "measures": [
      {
        "metric": "ncloc",
        "value": "43"
      },
      {
        "metric": "bugs",
        "value": "0",
        "bestValue": true
      },
      {
        "metric": "blocker_violations",
        "value": "0",
        "bestValue": true
      },
      {
        "metric": "info_violations",
        "value": "0",
        "bestValue": true
      },
      {
        "metric": "critical_violations",
        "value": "0",
        "bestValue": true
      },
      {
        "metric": "vulnerabilities",
        "value": "0",
        "bestValue": true
      },
      {
        "metric": "major_violations",
        "value": "0",
        "bestValue": true
      },
      {
        "metric": "code_smells",
        "value": "0",
        "bestValue": true
      },
      {
        "metric": "minor_violations",
        "value": "0",
        "bestValue": true
      },
      {
        "metric": "reliability_rating",
        "value": "1.0",
        "bestValue": true
      },
      {
        "metric": "security_rating",
        "value": "1.0",
        "bestValue": true
      }
    ]
  }
}

从上面的 .json 文件中,我需要获取指标及其各自的值:比如“bugs:0”。我确实找到了相关的博客,但有点困惑。

我的用例: 我想读取所有指标值,如果任何值是 <> 0,则执行 exit 1,否则执行 exit 0。我在下面尝试了一个指标。

if [  jq -r '.component.measures[].info_violations.value'!= 0 ]
then 
exit 1
else
exit 0

该代码没有抛出任何错误,但我确信这是不正确的逻辑,只是针对单个指标进行了尝试。现在我清楚了我的用例,我希望有人能帮助我。

我需要获取 measures[] 中项目的所有指标和相应值

【问题讨论】:

    标签: json shell


    【解决方案1】:

    您可以使用以下 JQ 过滤器来检查 any 的值是否等于 0

    .component.measures | any(.value == "0")
    

    可以使用 bash if 语句检查此输出,如示例中所示。

    [[ $(jq '.component.measures | any(.value == "0")' input) == "true" ]] && exit 1 || exit 0
    

    JqPlay

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-17
      • 1970-01-01
      • 2013-03-25
      • 2021-01-16
      • 1970-01-01
      • 2018-01-27
      • 1970-01-01
      • 2019-09-06
      相关资源
      最近更新 更多