I'm not able to get the Key attribute value from the JSON file using jq in shell [duplicate]

元气小坏坏 提交于 2020-02-16 13:17:24

问题


I'm trying to get the Key from the below JSON file:

I just executed the below command which will give the below JSON output

Command:

jq -r '.issues'

Output:

 {
    "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"
        }
    ]
}

I just want to get the output as below format and not sure how to get it.

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

Expected Output:

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

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

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

How can I get key value from each of the array and display like above? and JIRA-n will be increase based on the result.

When I run this command in shell but getting this error. And It works in the filter not in shell.

Command:

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"

Error: /tmp/jenkins5142826499545309380.sh: command substitution: line 46: syntax error near unexpected token .issues' /tmp/jenkins5142826499545309380.sh: command substitution: line 46:$readFile | reduce (.issues | to_entries[]) as {$key,$value} ({}; .["JIRA-($key + 1)"] = $value.key ))'

This is not duplicate, can you please remove it as duplicate and help me to get answer?


回答1:


After fixing the posted JSON, the following gives the desired result:

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

Notice that there is no need to use reduce.



来源:https://stackoverflow.com/questions/58093380/im-not-able-to-get-the-key-attribute-value-from-the-json-file-using-jq-in-shell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!