使用 jq 从 json 输出中获取键值

Using jq to fetch key value from json output

我有一个如下所示的文件:

{
  "repositories": [
   {
    "id": "156c48fc-f208-43e8-a631-4d12deb89fa4",
    "namespace": "rhel12",
    "namespaceType": "organization",
    "name": "rhel6.6",
    "shortDescription": "",
    "visibility": "public"
   },
   {
    "id": "f359b5d2-cb3a-4bb3-8aff-d879d51f1a04",
    "namespace": "rhel12",
    "namespaceType": "organization",
    "name": "rhel7",
    "shortDescription": "",
    "visibility": "public"
   }
  ]
 }

我只想在新行中获取每个名称值,以便我可以使用 while read -r line。 我只需要

rhel6.6 
rhel7

我正在使用 jq,但似乎不起作用:

jq -r '.[].name'

请在此处建议正确使用 jq

您需要通过 | 运算符组合过滤器:

$ jq -r '.[] | .[] | .name' test.json 
rhel6.6
rhel7

第一个 .[] 获取 repositories 数组。接下来的 .[] 获取 repositories 数组的所有项目。最后,.name 从数组项(对象)中提取属性。

请注意,第一个 .[] 适用于对象,因为它是一个记录在案的功能:

.[]
    If you use the .[index] syntax, but omit the index entirely, it
    will return all of the elements of an array...

    You can also use this on an object, and it will return all the
    values of the object.

您想查看存储库数组而不是将输入视为数组:

$ jq -r '.repositories[].name' file
rhel6.6
rhel7

这是另一种解决方案。假设要求

I want to get only name values with each of them in a new line so that I can use while read -r line.

Can you please how can i get output in format rhel12/rhel6.6 In other words, I need o/p in format namespace/name

如果数据在data.json中,那么命令

jq -M -r '.repositories[] | "\(.namespace)/\(.name)"' data.json

应该生产

rhel12/rhel6.6
rhel12/rhel7