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

mea*_*our 10 linux bash shell curl jq

我有一个文件如下所示:

{
  "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"
   }
  ]
 }
Run Code Online (Sandbox Code Playgroud)

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

rhel6.6 
rhel7
Run Code Online (Sandbox Code Playgroud)

我使用jq如下似乎不起作用:

jq -r '.[].name'
Run Code Online (Sandbox Code Playgroud)

请在这里建议正确使用jq

Rus*_*nov 18

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

$ jq -r '.[] | .[] | .name' test.json 
rhel6.6
rhel7
Run Code Online (Sandbox Code Playgroud)

第一个.[]获取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.
Run Code Online (Sandbox Code Playgroud)

  • @meallhour,`jq -r'。[] | .[] | [.命名空间,.name] | 加入(“/”)'test.json` (2认同)

tha*_*guy 14

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

$ jq -r '.repositories[].name' file
rhel6.6
rhel7
Run Code Online (Sandbox Code Playgroud)

  • 请分别发布新问题. (2认同)

jq1*_*727 6

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

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

请问我怎样才能得到格式rhel12/rhel6.6的输出换句话说,我需要格式命名空间/名称的o/p

如果数据在data.json然后命令

jq -M -r '.repositories[] | "\(.namespace)/\(.name)"' data.json
Run Code Online (Sandbox Code Playgroud)

应该产生

rhel12/rhel6.6
rhel12/rhel7
Run Code Online (Sandbox Code Playgroud)