Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq - iterate through dictionaries

My json knowledge is shaky, so pardon me if I use the wrong terminology.

I have input.txt which can be simplified down to this:

[
  {
    "foo1": "bar1",
    "baz1": "fizz1"
  },
  {
    "foo2": "bar2",
    "baz2": "fizz2"
  }
]

I want to iterate through each object via a loop, so I'm essentially hoping to tackle just the 1's first, then loop through the 2's, etc.

I thought it was something like:

jq 'keys[]' input.json | while read key ; do
    echo "loop --$(jq "[$key]" input.json)"
done

but that's giving me

loop 0
loop 1

where I would expect to see (spacing here is optional, not sure how jq would parse it):

loop { "foo1": "bar1", "baz1": "fizz1" }
loop { "foo2": "bar2", "baz2": "fizz2" }

What am I missing?

like image 205
Alex Avatar asked Dec 14 '25 03:12

Alex


2 Answers

No need to use bash, you can do this in jq itself:

jq -r 'keys[] as $k | "loop: \(.[$k])"' file.json

loop: {"foo1":"bar1","baz1":"fizz1"}
loop: {"foo2":"bar2","baz2":"fizz2"}
like image 51
anubhava Avatar answered Dec 16 '25 20:12

anubhava


What about using the -c option:

$ jq -c '.[]' file | sed 's/^/loop /'
loop {"foo1":"bar1","baz1":"fizz1"}
loop {"foo2":"bar2","baz2":"fizz2"}
like image 33
mickp Avatar answered Dec 16 '25 20:12

mickp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!