I'm not able to get the Key attribute value fr

2020-05-10 09:59发布

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?

标签: json shell unix jq
1条回答
Lonely孤独者°
2楼-- · 2020-05-10 10:02

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.

查看更多
登录 后发表回答