1

I want to list the keys of a nested object of my document. For example, I want the keys in the "a" object: "a1", "a2"

The sample document:

{
    "a": {
        "a1": "hello",
        "a2": "world"
    },

    "b": {
        "b1": "bonjour",
        "b2": "monde"
    }
}

I know I can use keys, but it seems to work only for the first level object: cat my.json | jq keys will output a, b.

So far I chain two calls with jq but I wonder if we can do it in one call ?

cat my.json | jq .a | jq keys --> a1, a2

Neekobus
  • 1,870
  • 1
  • 14
  • 18
  • Does this answer your question? [How to properly chain multiple jq statements together when processing json in the shell such as with curl?](https://stackoverflow.com/questions/47234312/how-to-properly-chain-multiple-jq-statements-together-when-processing-json-in-th) – Benjamin W. May 21 '20 at 13:19
  • @BenjaminW. it introduce the "filters" (pipe) notation, but it is not precisely answer my question. I think it worth a separated question. – Neekobus May 26 '20 at 09:53

1 Answers1

0

Ok I've just find out in a single call :

cat my.json | jq '.a|keys' 
a1, a2

Or even as @Inian suggested without the cat

jq '.a|keys' my.json 
a1, a2
Neekobus
  • 1,870
  • 1
  • 14
  • 18
  • 1
    The `cat` is superfluous here. `jq` can read from the file content directly (edited the answer) – Inian May 21 '20 at 13:11
  • 1
    @Inian the cat is superfluous, but is a better mental model for thinking about UNIX pipelines. It also reflects better the trial and error process that is often used to arrive at complex pipelines. And keeps the pipelines portable - e.g. one can iteratively construct a pipeline with a `cat test | jq 'foo' | something else`, make it as complex as one wishes, and then just replace the initial `cat test` with the actual `curl` or other data we wish to feed. – Manav Oct 16 '22 at 05:38
  • 1
    Something is wrong here, not sure if the question or answer got edited later, but when I execute `echo '{"a":{"a1":"hello","a2":"world"},"b":{"b1":"bonjour","b2":"monde"}}' | jq -c '.a|keys'`, I get `["a1","a2"]` not `["a1","b1"]` – fredfred Jul 27 '23 at 15:53
  • You are right @fredfred. Updated the question and the answer ! – Neekobus Jul 31 '23 at 14:51