簡體   English   中英

如何從嵌套(數組?)響應中獲取JQ名稱/值對?

[英]How to get JQ name/value pair from nested (array?) response?

我正在遍歷JSON響應文件,並在每次迭代中成功存儲名稱/值對。 我由於經驗不足而無法正確調整我的過濾器以訪問嵌套數組,這是響應的一部分,但是我失敗了。 我需要一些指導來設置正確的JQ過濾器

目的是循環瀏覽WEB-API curl命令的響應。 在我的案例中,在SonarQube中創建的問題並基於是否存在特定注釋,是否創建JIRA票證(不屬於示例)。

#!/usr/bin/env bash
SQIssues=$(curl --user user:pass https://sonarqube.domain.nl/api/issues/search?additionalFields=comments&statuses=OPEN&types=BUG&branch=master&componentKeys=project)
for k in $(jq '.issues | keys | .[]' <<< "$SQIssues"); do
        key=$(jq -r ".issues[$k].key" <<< "$SQIssues");
        status=$(jq -r ".issues[$k].status" <<< "$SQIssues");
        // TWO LINES BELOW NOT-OK
        comuser=$(jq -r ".issues[$k] | .comments[].login" <<< "$SQIssues");
        com=$(jq -r ".issues[$k] .comments[].markdown" <<< "$SQIssues");
        echo key="$key" and status="$status" and comment="$com" by user="$comuser";
        read -n 1 -s -r -p "Press any key to continue";
done

響應(正確捕獲了KEY和STATUS):

Press any key to continuekey=AWySAdI5-U8iL73rOJWx; and status=OPEN and comment= by user=
Press any key to continuekey=AWyMy9EK-U8iL73rOI-c; and status=OPEN and comment= by user=
Press any key to continuekey=AWyMy9Er-U8iL73rOI-d; and status=OPEN and comment= by user=

我成功獲得了特定級別的N / V對。 我無法從與“鍵”或“狀態”相同級別的“評論”數組中獲得N / V對

好=

ISSUES
-- KEY=xx
-- STATUS=xx

NOK =(評論下的n / v,深一層)

ISSUES
-- Comments
--- KEY=xx
--- MARKDOWN=xx

我假設“ comments”是一個數組。 我嘗試在循環期間存儲例如markdown值。

我正在嘗試使用的示例SQ響應主體(示例輸入)“ $ SQIssues ”這是完整響應的摘錄 ,發布於pastebin: https : //pastebin.com/MNubhfWM

{
key: "AWtQSFvOvmpNDcmJ7zeY",
rule: "javascript:S930",
severity: "CRITICAL",
component: "path/to/file.js",
project: "project-name",
line: 350,
hash: "9a8c7b5d9121757995511514602d1fd3",
textRange: {},
flows: [],
status: "OPEN",
message: "This function expects no arguments, but 1 was provided.",
effort: "10min",
debt: "10min",
author: "user@domain.nl",
tags: [],
comments: [
{
key: "AWxxXwIoRqbStspvKH2w",
login: "lmolenaar",
htmlText: "<a href="https://jira.domain.nl/browse/xxx-30093" target="_blank">https://jira.domain.nl/browse/xxx-30093</a>",
markdown: "https://jira.domain.nl/browse/xxx-30093",
updatable: true,
createdAt: "2019-08-08T15:15:47+0200"
}
],
creationDate: "2019-06-04T11:33:28+0200",
updateDate: "2019-08-08T15:15:47+0200",
type: "BUG",
organization: "default-organization",
fromHotspot: false
},

對於上面的輸入,我嘗試存儲comment:login和comment:markdown

  1. 使用您的pastebin JSON作為輸入,並注釋掉以//開頭的行和以read開頭的行,您的腳本實際上可以運行到完成。

  2. 由於comments是一個數組,因此編寫.comments[]有點冒險,因為.comments可能沒有一個元素。 如果符合您的要求,編寫.comments[0]風險會較小。

  3. 您的腳本會調用jq五次,但是修改它不會花費太多精力,因此jq僅被調用一次。 有關如何完成此操作的一些想法,請參見例如, 從JSON對象中提取2個值並用作使用jq和bash的循環變量

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM