简体   繁体   中英

Unable to fetch the JSON array values using jq in shell script

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:

"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.

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.

Given an array, you can use to_entries/1 to map the array an array of index and values. You could then map out to the keys and values you want on the object either using reduce or with_entries/1 .

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

https://jqplay.org/s/y6AFKg2dSM

.issues | with_entries({key: "JIRA-\(.key + 1)", value: .value.key})

https://jqplay.org/s/H2uxyFJn9E


It seems like you're using a version lesser than 1.5. You'll need to make some adjustments and remove the deconstruction.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM