Parse json object to bash
I want to write a bash script to loop through the array "certs". I read that I can use jq package to properly parse json but I dont want to use any package. Is there any other sleek way of handling this, please?
response = { "name": "Test", "certs": ["BSc", "MSc"]
} 3 1 Answer
You can use sed to create a list of the array contents with:
sed '/certs/!d;s/[^[]*\[//;s/,//;s/\]$//'This selects the line containing the string “certs” and deletes everything but the strings in the array from it. You can use Command Substitution to insert this list in e.g. a for loop:
for i in $(<json sed '/certs/!d;s/[^[]*\[//;s/,//;s/\]$//') do echo "$i"
doneThis loops over the items printing each of them on a new line.
An alternative to sed is grep to extract the list and tr to delete the commas:
grep -oP 'certs": \[\K.*(?=])' | tr -d ,Example run
The example text you gave is saved in a file named “json”.
$ for i in $(<json sed '/certs/!d;s/[^[]*\[//;s/,//;s/\]$//'); do echo "$i"; done
"BSc"
"MSc"