0

When I run the code below, it's iterating over each word in the key .serverParams instead of each instance of the key. (Echoing the line is not my ultimate intent, but just using it so I can see the output of each iteration)

for i in $(jq -r .servers[].serverParams ./servers.json); 
    do echo "$i"; 
    done

I can get my intended result with the following but it seems clunky:

for k in $(jq '.servers | keys| .[]' ./servers.json); 
    do jq .servers[$k].serverParams ./servers.json; 
    done
  • 1
    What does this have to do with JavaScript? – Pointy Sep 23 '20 at 17:56
  • @Pointy are JSON's not Javascript files? I can remove the tag. – Copy Run Start Sep 23 '20 at 17:58
  • 1
    JSON is a serialization format *based* on JavaScript, but it's not JavaScript. – Pointy Sep 23 '20 at 17:59
  • OK so `jq` is a JSON access tool, got it. – Pointy Sep 23 '20 at 18:00
  • So keep or remove the tag? – Copy Run Start Sep 23 '20 at 18:01
  • 1
    Without seeing what your JSON content looks like it's really hard to see what your asking. "Each instance of the key" is in particular not really clear. – Pointy Sep 23 '20 at 18:01
  • 1
    Your jq is fine. Your **bash** code is the problem. – Charles Duffy Sep 23 '20 at 18:07
  • 1
    `for item in $(thing-that-generates-lines)` is wrong; it string-splits the output of `thing-that-generates-lines` on all characters in IFS, not just newlines, and then expands them each as globs (so a `*` that's its own word will be replaced with a list of filenames in the current directory). Use a [BashFAQ #1](http://mywiki.wooledge.org/BashFAQ/001) `while read` loop instead. BTW, this issue is closely related to [BashPitfalls #1](http://mywiki.wooledge.org/BashPitfalls#for_f_in_.24.28ls_.2A.mp3.29). – Charles Duffy Sep 23 '20 at 18:07
  • @Pointy `{ "servers": [ { "Key1": "Some Value", "Key2": "Some Value", "Key3": "Some Value", "serverParams": "Some Value" }, { "Key1": "Some Value", "Key2": "Some Value", "Key3": "Some Value", "serverParams": "Some Value" } ] }` – Copy Run Start Sep 23 '20 at 18:10
  • Thanks guys, I'll re-write as a while loop. – Copy Run Start Sep 23 '20 at 18:11

0 Answers0