使用jq从json输出获取键值 [英] Using jq to fetch key value from json output

查看:227
本文介绍了使用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
}
]
}

我想获得只有名称值,每个都在一个新行,以便我可以使用而读-r行
我只需要

  rhel6.6 
rhel7



我使用的jq似乎不工作:

  jq -r'。[]。名称'

请建议正确使用jq这里

解决方案

您需要通过 |

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

code>。[] 提取 repository 数组。下一个。[] 获取存储库数组的所有项目。最后, .name 从数组项(对象)中提取属性。



注意,第一个。[] 在对象上工作,因为它是一个记录的功能:

 。 b $ b如果使用。[index]语法,但是完全省略了索引,它
将返回数组的所有元素...

也可以使用this一个对象,它将返回对象的所有
值。


I have a file that looks as below:

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

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

rhel6.6 
rhel7

I am using jq as follows which doesn't seem to work:

jq -r '.[].name'

Please suggest correct use of jq here

解决方案

You need to combine filters by means of | operator:

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

The first .[] fetches repositories array. The next .[] fetches all the items of the repositories array. Finally, .name extracts properties from the array items(objects).

Note, the first .[] works on object because it is a documented feature:

.[]
    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从json输出获取键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆