I am using bash
with jq
to parse data returned from https://ipinfo.io/json into an associative array. I found a nice example that almost does the job @ https://gist.github.com/awesome/b3f65084c70264e87be3e72ee8abd0e5
Whilst that code is able to parse most of the data, it fails when values contain multi-word strings. I suspect the issue has to do with putting quotes in the right place, but I don't know where. I've looked at the jq
documentation, and have a general idea, but the details have me stumped. I'm having a little difficulty understanding the interactions between the jq
pipes, templates and the reductions. (This is the first time I'm using jq
, though I'm pretty solid on regex
.)
My version of the code is:
locationResult=$(curl -s 'https://ipinfo.io/json')
arrayAsString=$(echo "$locationResult" | jq --raw-output '. | to_entries | map("[\(.key)]=\(.value)") | reduce .[] as $item ("associativeArray=("; . + $item + " ") + ")"')
declare -A "$arrayAsString"
echo ${associativeArray[org]}
For my location, org
returns a company name that is multi-worded, and this causes declare -A "$arrayAsString"
to generate a warnings/errors, and echo ${associativeArray[org]}
to produce only the first word for the org
field.
I have tried quoting the jq
result as per the Assigning jq output to bash array when json value contains spaces question but that didn't work.
Any help here would be appreciated.
wait
? I can't notice anything running in the background. – aviro Dec 14 '21 at 08:28<(...)
process substitution runs in the background. Usingwait
lets you retrieve its exit status and exit the script ifcurl
orjq
fails (see also thepipefail
option). – Stéphane Chazelas Dec 14 '21 at 10:00line 15: wait: pid 10083 is not a child of this shell
– aviro Dec 14 '21 at 12:45$!
contains the pid of the process substitution. However, you need bash 4.4 or newer to be able to wait on it. I've added a note about that. – Stéphane Chazelas Dec 14 '21 at 12:55to_entries[]
and[.key, .value
? – gone Dec 15 '21 at 02:58del(."") |
into the pipeline beforeto_entries
and after. |
. – gone Dec 15 '21 at 03:08.
and use"${ipinfo[.ip]}"
instead of"${ipinfo[ip]}"
(or switch to a better designed shell, or again to a proper programming language). – Stéphane Chazelas Dec 15 '21 at 05:48