Parse JSON to array in a shell script

前端 未结 3 2110
孤独总比滥情好
孤独总比滥情好 2020-12-01 18:49

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:

{
  \"         


        
3条回答
  •  孤街浪徒
    2020-12-01 19:13

    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.

提交回复
热议问题