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

新手上路,请多包涵

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

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

原文由 meallhour 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

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

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

原文由 Ruslan Osmanov 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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

原文由 that other guy 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题