加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

regex – 如何使用curl和sed从短json查询中提取单个元素

发布时间:2020-12-14 00:04:01 所属栏目:Linux 来源:网络整理
导读:我正在研究一个简短的bash脚本来从curl响应中获取 JSON元素. curl -H "api_key:[API_PASSWORD]" http://api.wordnik.com/v4/word.json/button/pronunciations?sourceDictionary=macmillantypeFormat=IPAuseCanonical=false 收益: [{"id":0,"seq":0,"raw":"?
我正在研究一个简短的bash脚本来从curl响应中获取 JSON元素.

curl -H "api_key:[API_PASSWORD]" http://api.wordnik.com/v4/word.json/button/pronunciations?sourceDictionary=macmillan&typeFormat=IPA&useCanonical=false

收益:

[{"id":0,"seq":0,"raw":"?b?t(?)n","rawType":"IPA"},{"id":0,"rawType":"IPA"}]

我正试图提取“b?t(?)n”元素.

虽然我不熟悉正则表达式,但我认为我应该使用这个字符串替换:

/.*"(.*)",/

我正在尝试运行以下命令,但它似乎不起作用:

curl -H "api_key:[API_KEY]" http://api.wordnik.com/v4/word.json/button/pronunciations?sourceDictionary=macmillan&typeFormat=IPA&useCanonical=false | sed /.*"(.*)",1/

我确定有一些事情我做错了,经过几个小时的搜索和阅读正则表达式和bash我没有选择.

我不需要使用sed,我只是在bash命令行中寻找一种快速的方法,这样我就可以在mac上的TextExpander脚本中实现它.

解决方法

使用STRING:REGEXP从json字符串中提取值:

string=$(curl -H "api_key:[API_PASSWORD]" http://api.wordnik.com/v4/word.json/button/pronunciations?sourceDictionary=macmillan&typeFormat=IPA&useCanonical=false)
raw=$(expr "$string" : '.*"raw":"([^"]*)"')

echo $raw

见man expr:

STRING : REGEXP
          anchored pattern match of REGEXP in STRING

   Pattern matches return the string matched between (  and  )  or null

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读