使用jq从JSON输出中提取键值对

59

我有一个文件,内容如下:

{
  "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"
   }
  ]
 }
我希望每个名称的值都在新行中,并且保留HTML标记,以便我可以使用while read -r line。我只需要

rhel6.6 
rhel7
我使用以下方式来使用 jq,但似乎不起作用:
jq -r '.[].name'
请在此处提供jq的正确用法
3个回答

104

您需要使用|运算符来组合过滤器:

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

1
谢谢您的回复。您能告诉我如何以“rhel12/rhel6.6”格式获取输出吗?换句话说,我需要以“namespace/name”的格式输出。 - meallhour
2
@meallhour,jq -r '.[] | .[] | [.namespace,.name] | join("/")' test.json - Ruslan Osmanov

37
您需要查看存储库数组,而不是将输入视为数组:
$ jq -r '.repositories[].name' file
rhel6.6
rhel7

16

这里是另一种解决方案。假定要求如下:

我想要仅获取每个名称的值,并将它们在新行中使用 while read -r line 命令。

请问如何以 rhel12/rhel6.6 的格式输出?换句话说,我需要以 namespace/name 的格式输出结果。

如果数据在 data.json 中,则使用以下命令:

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

应该产生

rhel12/rhel6.6
rhel12/rhel7

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接