我无法在shell

时间:2019-09-25 07:35:15

标签: json shell unix jq

我正在尝试从下面的JSON文件中获取密钥:

我刚刚执行了以下命令,它将给出以下JSON输出

命令:

jq -r '.issues'

输出:

 {
    "expand": "schema,names",
    "startAt": 0,
    "maxResults": 50,
    "total": 4,
    "issues": [{
            "expand": "operations,versionedRepresentations,editmeta,changelog,renderedFields",
            "id": "1999875",
            "self": "https://amazon.kindle.com/jira/rest/api/2/issue/1999875",
            "key": "KINDLEAMZ-67578"
        },
        {
            "expand": "operations,versionedRepresentations,editmeta,changelog,renderedFields",
            "id": "2019428",
            "self": "https://amazon.kindle.com/jira/rest/api/2/issue/2019428",
            "key": "KINDLEAMZ-68661"
        },
        {
            "expand": "operations,versionedRepresentations,editmeta,changelog,renderedFields",
            "id": "2010958",
            "self": "https://amazon.kindle.com/jira/rest/api/2/issue/2010958",
            "key": "KINDLEAMZ-68167"
        }
    ]
}

我只想获取以下格式的输出,不确定如何获取。

https://jqplay.org/s/0IfiBoskG5

预期输出:

{
"JIRA-1":"KINDLEAMZ-67578",

"JIRA-2":"KINDLEAMZ-68661",

"JIRA-3":"KINDLEAMZ-68167"
}

如何从每个数组中获取键值并显示如上?并根据结果增加JIRA-n。

当我在shell中运行此命令但出现此错误时。并且它在过滤器中而不在外壳中工作。

命令:

sudo apt-get update

sudo apt-get install jq

readFile=$(cat response.json)

echo "$readFile"  // It contains the above JSON file that mentioned as output

getResponse=$($readFile | reduce (.issues | to_entries[]) as {$key,$value} ({}; .["JIRA-\($key + 1)"] = $value.key ))

echo "$getResponse"

错误: /tmp/jenkins5142826499545309380.sh:命令替换:第46行:意外令牌.issues' /tmp/jenkins5142826499545309380.sh: command substitution: line 46: $ readFile |附近的语法错误减少(.issues | to_entries [])为{$ key,$ value}({};。[“ JIRA-($ key + 1)”] = $ value.key))'

这不是重复项,您能否将其删除为重复项并帮助我获得答案?

1 个答案:

答案 0 :(得分:0)

修复发布的JSON之后,以下内容将提供所需的结果:

.issues
| with_entries( .key |= "JIRA-\(. + 1)" | .value |= .key )

请注意,无需使用reduce