Unable to fetch the JSON array values using jq in

2020-02-16 04:37发布

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.

1条回答
混吃等死
2楼-- · 2020-02-16 05:38

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
)
查看更多
登录 后发表回答