在Bash中提取JSON值 [英] Extract JSON value in Bash
问题描述
在Bash中,我将响应数据保存到一个变量中.
In the Bash I saved response data into a variable.
结果如下:
{"token_type":"Bearer","access_token":"022-8baa5324-f57b-445d-c5ec-821c63a5fd35","expires_in":3600,"scope":"any-website.com"}
现在我想将访问令牌的值提取到另一个变量中.
Now I want to extract the value of the access token into an other var.
在Linux中,我以这种方式解决了该问题,并且有效:
In Linux I solved that in this way and it works:
echo "$response_json" | grep -oP '(?<="access_token":")[^"]*'
结果我得到:
022-8baa5324-f57b-445d-c5ec-821c63a5fd35
我的问题是MacOS不再支持grep参数P
(Perl表达式).参数E
不适用于该表达式.
My problem is that MacOS does not support the grep parameter P
(Perl expression) anymore. Parameter E
does not work with that expression.
我希望在不安装其他Bash工具的情况下提供解决方案方面的帮助.
I would appreciate any help with a solution without requiring to install additional Bash tools.
推荐答案
每个人都说他们不想安装新工具,但实际上,像grep
这样的面向行的工具并不是专门为处理结构化文本而设计的.像JSON.如果要使用JSON,请获取旨在处理JSON的工具.
Everyone says they don't want to install new tools, but really, line-oriented tools like grep
simply weren't designed to cope with structured text like JSON. If you are going to work with JSON, get tools designed to process it.
jq
是这样的一种选择:
jq
is one such option:
$ echo "$response_json" | jq -r '.access_token'
022-8baa5324-f57b-445d-c5ec-821c63a5fd35
这篇关于在Bash中提取JSON值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!