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"]
  • 2
    I don't think you should attempt to build your own fragile json parser just because you don't want to use the proper tool for the job. While JSON looks simple at first sight, there's still a lot to consider to parse it reliably and not break if the output looks slightly different than usual for some reason. If you want to avoid installing packages, use a scripting language with native JSON support like Python instead of Bash. – Byte Commander May 5 at 15:39
  • @ByteCommander You can’t parse HTML with Regex, but JSON? Any link I could add to my answer? – dessert May 5 at 15:47
  • 1
    @dessert not sure if JSON would classify as context-free or context sensitive in the Chomsky hierarchy, but you have the same problems of nested structures and escaped characters that you see in HTML. So same as there, regex can find small subsets of the language, but not parse complex structures. Besides, the effort to make it reliable is not justified IMO as there exist ready-to-use and battle-proven alternatives. – Byte Commander May 5 at 16:19

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"

This 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.