0

I'm building a script to process JSON for specifc Chef/node data. I need to get the name of each object as it will be different every time. Typically I use jsawk but this is only helpful if you know the name of the object.

A solution should work on either of the below examples:

{"keepalived":{"role":"MASTER","vip":"192.168.4.113"},"mysql":{"service_name":"singularitydb"},"haproxy":{"role":"MASTER"}}

Should return: keepalived,mysql,haproxy

{"nginx":{"attribute":"standalone"},"haproxy":{"role":"MASTER"}}

Should return: nginx,haproxy

1 Answer 1

5

Use jq:

echo "$JSON" | jq 'keys'
Sign up to request clarification or add additional context in comments.

4 Comments

it won't work for objects inside objects, but maybe author doesn't need that
Neither example indicates that is required. Both ask for the top-level keys of an object.
I'll give it to you for introducing me to jq...but i really wanted to iterate over the keys. Did it with this: jslength=$(echo $attributes | jq 'keys | length') for ((i=0; i<$jslength; i++)); do result=$(echo $attributes | jq 'keys' | jq ".[$i]") echo $result done
You should be clearer about what you ask for: echo "$attributes" | jq 'keys | .[]' is the equivalent of the code in your comment. Depending on what you actually want to do with each key while iterating, there may also be something in jq you can use.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.