0

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)

2 Answers 2

2

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]}"
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh, I forgot the backticks when I wrote it.
1

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"

1 Comment

Thanks, more manageable than my original idea. Although I ended up with test=tail -n1 output | awk -F'[,:\"]' '{ print $9 }'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.