Json

使用查詢列印來自 json 文件的相鄰值

  • August 25, 2022

我有以下 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": "XXXXXX@XXXXXX.com",
     "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 進行操作,但需要更多步驟來添加腳本。

我們可以從數組中的每個元素中提取val和值,並將它們格式化為字元串,如下所示:count``values``facets``key=value

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

操作員將@sh確保字元串的格式正確,以便由 shell 作為變數賦值、引用字元串和轉義可能有問題的字元來執行。

.count // 0確保在缺少、 或0時使用該值。.count``null``false

給定上面的文件,這個命令會產生

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

引用自:https://unix.stackexchange.com/questions/714793