无法在Shell脚本中使用jq提取JSON数组值 [英] Unable to fetch the JSON array values using jq in shell script
问题描述
我正在尝试从下面的JSON文件中获取密钥:
I'm trying to get the Key from the below JSON file:
我刚刚执行了以下命令,它将给出以下JSON输出
I just executed the below command which will give the below JSON output
命令:
jq -r '.issues'
输出:
"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.
预期输出:
{
"JIRA-1":"KINDLEAMZ-67578",
"JIRA-2":"KINDLEAMZ-68661",
"JIRA-3":"KINDLEAMZ-68167"
}
如何从每个数组中获取键值并像上面一样显示?并根据结果增加JIRA-n.
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.
推荐答案
给出一个数组,您可以使用to_entries/1
将该数组映射为索引和值的数组.然后可以使用reduce
或with_entries/1
映射到对象上想要的键和值.
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
似乎您使用的版本小于1.5.您需要进行一些调整并删除解构.
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
)
这篇关于无法在Shell脚本中使用jq提取JSON数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!