bash 如何使用 curl 和 sed 从简短的 json 查询中提取单个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7473951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use curl and sed to extract a single element from a short json query
提问by Chris Kinniburgh
I'm working on a short bash script to grab a JSON element from a curl response.
我正在编写一个简短的 bash 脚本来从 curl 响应中获取一个 JSON 元素。
curl -H "api_key:[API_PASSWORD]" http://api.wordnik.com/v4/word.json/button/pronunciations?sourceDictionary=macmillan&typeFormat=IPA&useCanonical=false
returns:
返回:
[{"id":0,"seq":0,"raw":"?b?t(?)n","rawType":"IPA"},{"id":0,"seq":0,"raw":"?b?t(?)n","rawType":"IPA"}]
I'm trying to extract the "?b?t(?)n" element.
我正在尝试提取“?b?t(?)n”元素。
Though I'm unfamiliar with regex, I think I should be using a substitution with this string:
虽然我不熟悉正则表达式,但我认为我应该使用以下字符串替换:
/.*"(.*)",/
I'm trying to run the following command, but it doesn't seem to work:
我正在尝试运行以下命令,但它似乎不起作用:
curl -H "api_key:[API_KEY]" http://api.wordnik.com/v4/word.json/button/pronunciations?sourceDictionary=macmillan&typeFormat=IPA&useCanonical=false | sed /.*"(.*)",/
I'm sure there are a few things I'm doing wrong, and after a few hours of searching and reading up on regex and bash I'm out of options.
我确定有几件事我做错了,经过几个小时的搜索和阅读正则表达式和 bash 后,我别无选择。
I don't need to be using sed, I am simply looking for a quick way of doing this in a bash command line so that I can implement it in a TextExpander script on the mac.
我不需要使用 sed,我只是在 bash 命令行中寻找一种快速执行此操作的方法,以便我可以在 mac 上的 TextExpander 脚本中实现它。
回答by Arnaud Le Blanc
Use STRING : REGEXPto extract the value from the json string:
用于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
See man expr:
见man expr:
STRING : REGEXP
anchored pattern match of REGEXP in STRING
Pattern matches return the string matched between \( and \) or null
回答by jpickard
Regular expressions may not be the right thing to use. http://www.codinghorror.com/blog/2008/06/regular-expressions-now-you-have-two-problems.html
正则表达式可能不适合使用。 http://www.codinghorror.com/blog/2008/06/regular-expressions-now-you-have-two-problems.html
On Ubuntu 9.10:
在 Ubuntu 9.10 上:
$ sudo apt-get install jsonlib-perl
$ curl -quiet 'http://api.wordnik.com/v4/word.json/button/pronunciations?sourceDictionary=macmillan&typeFormat=IPA&useCanonical=false' | perl -e 'use JSON; print JSON->new->allow_nonref->decode(<>)->{raw}'

