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

lymnna71  于 2022-12-11  发布在  Linux
关注(0)|答案(3)|浏览(475)

我有一个文件,看起来如下:

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

ryoqjall

ryoqjall1#

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

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

第一个.[]获取repositories数组。下一个.[]获取repositories数组的所有项。最后,.name从数组项(对象)中提取属性。
注意,第一个.[]可以在object上运行,因为它是一个已记录的功能:

.[]
    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.
ercv8c1e

ercv8c1e2#

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

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

kgsdhlau3#

这是另一个解决方案。假设要求
我只想得到name值,每个值都在一个新行中,这样我就可以在读取-r行时使用。
您能告诉我怎样才能得到rhel 12/rhel6.6格式输出吗换句话说,我需要命名空间/名称格式o/p
如果数据在data.json中,则命令

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

应产生

rhel12/rhel6.6
rhel12/rhel7

相关问题