使用查询打印 json 文件中相邻的值

使用查询打印 json 文件中相邻的值

我有以下 json 文件

    {
  "total": 64,
  "p": 1,
  "ps": 1,
  "paging": {
    "pageIndex": 1,
    "pageSize": 1,
    "total": 64
  },
  "effortTotal": 216,
  "issues": [
    {
      "key": "AX8lZNY1h5xTw2fmJuX6",
      "rule": "xml:S125",
      "severity": "MAJOR",
      "component": "X8lXT9yjCYHsI0QujFF:pom.xml",
      "project": "X8lXT9yjCYHsI0QujFF",
      "line": 29,
      "hash": "6e7405674b46c05cd7d7fc9433dbb323",
      "textRange": {
        "startLine": 29,
        "endLine": 33,
        "startOffset": 6,
        "endOffset": 22
      },
      "flows": [],
      "status": "OPEN",
      "message": "Remove this commented out code.",
      "effort": "5min",
      "debt": "5min",
      "author": "[email protected]",
      "tags": [
        "unused"
      ],
      "creationDate": "2021-12-19T18:54:28+0100",
      "updateDate": "2022-02-23T08:03:15+0100",
      "type": "CODE_SMELL",
      "scope": "MAIN"
    }
  ],
  "components": [
    {
      "key": "X8lXT9yjCYHsI0QujFF:pom.xml",
      "enabled": true,
      "qualifier": "FIL",
      "name": "pom.xml",
      "longName": "pom.xml",
      "path": "pom.xml"
    },
    {
      "key": "X8lXT9yjCYHsI0QujFF",
      "enabled": true,
      "qualifier": "TRK",
      "name": "my-app",
      "longName": "my-app"
    }
  ],
  "facets": [
    {
      "property": "types",
      "values": [
        {
          "val": "BUG",
          "count": 34
        },
        {
          "val": "CODE_SMELL",
          "count": 30
        },
        {
          "val": "VULNERABILITY",
          "count": 0
        }
      ]
    }
  ]
}

我想打印如下值

BUG=34

我尝试了下面的解决方法,但它没有按照我的要求打印

jq -r '.facets[].values[0].val,.facets[].values[0].count' file.json

打印如下

BUG
34

但我必须再次提及 [0] 的 BUG [1] 的 CODE_SMELL 等等

有什么方法可以做到这一点,使其打印如下

BUG=34
CODE_SMELL:30
VULNERABILITY:0 (it will be null but I can put condition to print it is as zero in shell script while referring it as variable)

请指导我是 JQ 的新手,我知道如何使用 sed 来完成它,但它需要更多步骤来添加到脚本中。

答案1

我们可以从数组中的每个元素中提取val和值,并将它们格式化为字符串,如下所示:countvaluesfacetskey=value

jq -r '.facets[].values[] | "\(.val)=\(.count // 0 | @sh)"' file

@sh运算符将确保字符串格式正确,以便由 shell 作为变量赋值、引用字符串并转义可能有问题的字符来执行。

.count // 0将确保在缺少 、或0时使用该值。.countnullfalse

鉴于上面的文档,此命令将产生

BUG=34
CODE_SMELL=30
VULNERABILITY=0

评估上述命令的输出将创建 shell 变量:

$ unset -v BUG CODE_SMELL VULNERABILITY  # clears the variables
$ eval "$( jq -r '.facets[].values[] | "\(.val)=\(.count // 0 | @sh)"' file )"
$ echo "$BUG"
34
$ printf '%s\n' "$BUG" "$CODE_SMELL" "$VULNERABILITY"
34
30
0

相关内容