condor126 condor126 - 3 months ago 22
Bash Question

use shell script to parse json returned by a restful service

I have a Restful web service with a URL like "http://myhost:5000/getname" to return a JSON string like this:

{"firstName": "john", "lastName": "doe"}


Now that I need to use Linux shell to call the web service and parse the returned JSON string to get the first name and last name. They need to be stored into two variebles and printed out.

I am new to shell scripting, so would some one please kindly share your thoughts? Thanks!

Answer

Best bet would be to use any json aware tool. However here is solution using awk and eval , later should be avoided as much as possible.

sample input file:

cat file.json
{"firstName": "john", "lastName": "doe"}

Solution:

eval $(awk 'BEGIN{FS=RS=","} {gsub( /{|}|"/,"");split($0,a,":");print a[1] "="a[2]} ' file.json | tr -d ' ')

echo $firstName
john
echo $lastName
doe

OR using tr and xargs

eval $(tr '[[:punct:]]' ' ' < file.json  |tr -s ' ' |xargs -n2 |tr ' ' '=' )
echo $firstName
john
echo $lastName
doe