1

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": []
>     }   } ]

When I tried to filter by keys:

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

==> null

Or even list out the keys:

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

[ 0 ]

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

Inian
  • 80,270
  • 14
  • 142
  • 161
jellycat
  • 57
  • 2
  • You should consider reading [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) and [What does it mean when an answer is "accepted"?](https://stackoverflow.com/help/accepted-answer) – Inian Apr 10 '19 at 16:13

1 Answers1

0

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'

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

jq --arg host "host001" '.[][] | to_entries | map(select(.key==$host)) | from_entries'
Inian
  • 80,270
  • 14
  • 142
  • 161