【问题标题】:Using jq to fetch key value from json output使用 jq 从 json 输出中获取键值
【发布时间】:2017-02-09 10:42:52
【问题描述】:

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

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

【问题讨论】:

    标签: linux bash shell curl jq


    【解决方案1】:

    你需要通过|操作符组合过滤器:

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

    第一个 .[] 获取 repositories 数组。下一个.[] 获取repositories 数组的所有项目。最后,.name 从数组 items(objects) 中提取属性。

    请注意,第一个 .[] 适用于对象,因为它是一个文档化功能:

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

    【讨论】:

    • 感谢您的回复。请问我怎样才能得到rhel12/rhel6.6格式的输出,换句话说,我需要namespace/name格式的o/p
    • @meallhour, jq -r '.[] | .[] | [.namespace, .name] | join("/")' test.json
    【解决方案2】:

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

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

    【讨论】:

    • 感谢您的回复。请问我怎样才能得到rhel12/rhel6.6格式的输出,换句话说,我需要namespace/name格式的o/p
    • 请单独发布新问题。
    【解决方案3】:

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

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

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

    如果数据在data.json 中,那么命令

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

    应该产生

    rhel12/rhel6.6
    rhel12/rhel7
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-17
      • 2021-01-21
      • 2018-09-08
      • 1970-01-01
      • 2014-05-31
      相关资源
      最近更新 更多