I\'m trying to parse a JSON object within a shell script into an array.
e.g.: [Amanda, 25, http://mywebsite.com]
The JSON looks like:
{
\"
You can use a sed one liner to achieve this:
array=( $(sed -n "/{/,/}/{s/[^:]*:[[:blank:]]*//p;}" json ) )
Result:
$ echo ${array[@]}
"Amanda" "25" "http://mywebsite.com"
If you do not need/want the quotation marks then the following sed will do away with them:
array=( $(sed -n '/{/,/}/{s/[^:]*:[^"]*"\([^"]*\).*/\1/p;}' json) )
Result:
$ echo ${array[@]}
Amanda 25 http://mywebsite.com
It will also work if you have multiple entries, like
$ cat json
{
"name" : "Amanda"
"age" : "25"
"websiteurl" : "http://mywebsite.com"
}
{
"name" : "samantha"
"age" : "31"
"websiteurl" : "http://anotherwebsite.org"
}
$ echo ${array[@]}
Amanda 25 http://mywebsite.com samantha 31 http://anotherwebsite.org
UPDATE:
As pointed out by mklement0 in the comments, there might be an issue if the file contains embedded whitespace, e.g., "name" : "Amanda lastname". In this case Amanda and lastname would both be read into seperate array fields each. To avoid this you can use readarray, e.g.,
readarray -t array < <(sed -n '/{/,/}/{s/[^:]*:[^"]*"\([^"]*\).*/\1/p;}' json2)
This will also take care of any globbing issues, also mentioned in the comments.