使用jq按对象名称过滤JSON [英] Filtering JSON by object name using jq

查看:70
本文介绍了使用jq按对象名称过滤JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用jq按键进行过滤.

I'm unable to filter by keys using jq.

# /home/test/show_param_db.sh -p memory -h host00* -f json | jq '.[]'

> [   {
>     "host001": {
>       "status": "OK",
>       "msg": "",
>       "data": [
>         {
>           "hi_shared_memory_address": "0"
>         },
>         {
>           "memory_max_target": "1G"
>         },
>         {
>           "memory_target": "1G"
>         },
>         {
>           "shared_memory_address": "0"
>         }
>       ]
>     },
>     "host002": {
>       "status": "ERROR",
>       "msg": "su: user oracle does not exist",
>       "data": []
>     }   } ]

当我尝试按键过滤时:

# /home/test/show_param_db.sh -p memory -h host00* -f json | jq -r '.["host001"]'

==>空

甚至列出密钥:

# /home/test/show_param_db.sh -p memory -h host00* -f json | jq -r '.[]' |  jq -r 'keys'

[0]

我希望通过主机名获取json.感谢所有建议.

I'm hoping to get json by hostname. Thanks for all suggestions.

推荐答案

您是否只是在寻找与 host001 相对应的对象?您可以使用 to_entries from_entries 在键/值对和JSON对象之间进行映射,并使用之间的 select()表达式来匹配所需的主机

Are you looking only to get the object corresponding to host001? You can use to_entries and from_entries to map between key/value pairs and JSON objects and use a select() expression between to match the host needed

jq '.[][] | to_entries | map(select(.key=="host001")) | from_entries'

要使其具有动态性,请将名称作为单独的arg传递

To make it dynamic, pass the name as a separate arg,

jq --arg host "host001" '.[][] | to_entries | map(select(.key==$host)) | from_entries'

这篇关于使用jq按对象名称过滤JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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