Reputation: 2200
I need to extract some information from json strings in bash. The json-strings are like
{"ok":true,"id":"af1aa5cef5dc0c86fd734ff3d42a8188","rev":"1-f28941b049d7d356ae113fa061ddfe1f"}
(outputs from a couchdb insert)
I want to grab just the id, so I tried to
$IFS=;,\"
json=tail -n1 output
echo $json
\\ { ok true id af1aa5cef5dc0c86fd734ff3d42a8188 rev 1-f28941b049d7d356ae113fa061ddfe1f }
So, so far, all seems fine and dandy, but, if I try to access an element, ${json[0]} returns the entire string, whereas all other ${json[n]}s are empty.
On the other hand,
for i in $json;
do echo $i
done
Works with each element of $json...
I must be doing something wrong, but what?
(And yes, I do know this kind of "parsing" of a json string will get me into problems with something just slightly more complicated - but for these strings it should work fine - I thought)
Upvotes: 0
Views: 85
Reputation: 242383
To assing to an array, you have to use parentheses. The line where you capture the output of tail
is also invalid, BTW.
json=( $(tail -n1 output) )
echo "${json[2]}"
Upvotes: 2
Reputation: 3880
You can use awk:
$ echo '"ok":true,"id":"af1aa5cef5dc0c86fd734ff3d42a8188","rev":"1-f28941b049d7d356ae113fa061ddfe1f"}' | awk -F, '{ print $2 }'
"id":"af1aa5cef5dc0c86fd734ff3d42a8188"
You can also you two delimiters with awk
$ awk -F'[,:]' '{ print $4 }' your_json_file.json
"af1aa5cef5dc0c86fd734ff3d42a8188"
Upvotes: 1