使用Shell脚本解析宁静服务返回的json [英] use shell script to parse json returned by a restful service

查看:66
本文介绍了使用Shell脚本解析宁静服务返回的json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Restful Web服务,其URL类似于" http://myhost:5000/getname "返回这样的JSON字符串: {"firstName":"john","lastName":"doe"}

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"}

现在,我需要使用Linux shell来调用Web服务并解析返回的JSON字符串以获取名字和姓氏.它们需要存储在两个变量中并打印出来.

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.

我是Shell脚本的新手,所以请有人分享您的想法吗?谢谢!

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

推荐答案

最好的选择是使用任何支持json的工具.但是,这里是使用 awk eval 的解决方案,应尽可能避免以后使用.

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.

样本输入文件:

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

解决方案:

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

echo $firstName
john
echo $lastName
doe

使用 tr xargs

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

这篇关于使用Shell脚本解析宁静服务返回的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆