【问题标题】:jq: filter input based on if key ends with specified stringjq:根据键是否以指定字符串结尾过滤输入
【发布时间】:2018-07-31 22:38:20
【问题描述】:

我把这个 JSON 数据弄乱了,我需要提取类型列表:

{
  "token/": {
    "accessor": "auth_token_909d6a81",
    "config": {
      "default_lease_ttl": 0,
      "max_lease_ttl": 0
    },
    "description": "token based credentials",
    "local": false,
    "seal_wrap": false,
    "type": "token"           <-- I need to extract this value ...
  },
  "userpass/": {
    "similar_to": {
      "above": null
    },
    "description": "",
    "local": false,
    "seal_wrap": false,
    "type": "userpass"        <-- ... and this one
  },
  "request_id": "f2a4c135-f699-f29d-ca7c-3320dce0a550",
  "more_keys": "more_values",
  "data": {
    "more_data": {
      "even_more_data": "snipped"
    }
  },
  "you_get_the": "idea"
}

抱歉,内联 cmets 在复制和粘贴时弄乱了数据,但这似乎是阐明我的目标的最佳方式: 对于所有以/ 结尾的根键,我需要.type 的值,这样上例的最终结果就是token userpass

我设法为根键创建了一个有效的过滤器:

host:~ user$ jq -r '. | keys[] | endswith("/")' <<< "${json_data}"
false
false
false
true
true
false

我可以使用该过滤器来仅获取所需的键,但这只是键本身,而不是它们下面的整个数据结构:

host:~ user$ jq -r '. | keys[] | select(. | endswith("/"))' <<< "${json_data}"
token/
userpass/

我似乎无法将所有这些放在一起......

谁能帮帮我?

【问题讨论】:

    标签: json filter key jq


    【解决方案1】:

    to_entries 值得了解,尤其是因为它通常会导致易于阅读(无变量)的管道,如下所示:

    to_entries[] | select(.key|endswith("/")) | .value.type
    

    【讨论】:

    • 改天,另一个问题 - 你的帖子就是答案。确实值得了解! ?
    【解决方案2】:

    jq解决方案:

    jq -r '. as $o | keys_unsorted[] | select(endswith("/")) | $o[.].type' file.json
    

    输出:

    token
    userpass
    

    【讨论】:

    • 只要你做对了,它就起作用了?谢谢你的快速帮助! ?
    猜你喜欢
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    • 2011-06-06
    • 1970-01-01
    • 2021-06-06
    • 2013-12-11
    • 2014-02-09
    相关资源
    最近更新 更多