|
|
聪明伶俐的红薯 · 血源詛咒 - 萌娘百科 萬物皆可萌的百科全書· 4 月前 · |
|
|
心软的铁板烧 · 【考古花少2】删减画面:宁静、陈意涵、井柏然 ...· 1 年前 · |
|
|
打酱油的木瓜 · 宝马i3缺点值得买吗_宝马i3怎么样_懂车帝· 2 年前 · |
|
|
魁梧的白开水 · 同态加密为什么能被称为密码学的“圣杯”? ...· 2 年前 · |
|
|
文质彬彬的酸菜鱼 · 十八线主播在线算命,爆出影帝隐婚生子后火了 ...· 2 年前 · |
我希望在Linux中使用Grep从JSON响应中提取oid值,并将其存储在变量$oid中。JSON存储在变量$Response中
我的代码
oid= $Response | grep -Po '"oid": *\K"[^"]\*"'
My JSON (简写)
{
"count": 1,
"items": [{
"oid": "xyzxyzxyzxyzxyzxyzxyz",
"creationDate": "2019-02-05T02:21:08.662+0000"
}
实际行为 :当我回送$oid时,它是空的(例如,Grep没有从JSON中提取任何值)
预期行为 :$oid保存从JSON中提取的样例(在本例中是
发布于 2022-07-26 13:29:29
由于OP清楚地提到了json解析器不能被使用,所以在GNU
grep
中不能这样回答。用GNU
grep
编写和测试,仅显示示例。而且,专家们总是建议使用json解析器,所以如果您有兴趣的话。
echo "$Response" | grep -ozP '(^|\n){\n"count":\s+[0-9]+,\n"items":\s+\[{\n\s+"oid":\s+"\K[^"]*'
输出如下:
xyzxyzxyzxyzxyzxyzxyz
regex的
解释:
添加了对上述regex使用的详细说明,它仅用于解释目的,如需使用,请参阅上面的GNU
grep
命令。
(^|\n){\n ##Matching new line OR starting here followed by { and new line.
"count":\s+ ##Matching "count": followed by 1 or more spaces.
[0-9]+,\n ##Matching 1 or more digits followed by comma followed by new line.
"items":\s+ ##Matching "items": followed by 1 or more spaces.
\[{\n\s+ ##matching literal [ followed by { new line and spaces.
"oid":\s+" ##Matching "oid": followed by 1 or more spaces followed by " here.
\K ##Here is GNU grep's GREAT option \K which helps us to forget previous match.
##Basically match everything but forget its value so that we can get only required values.
[^"]* ##Match everything just before next occurrence of " here.
发布于 2022-07-26 18:58:48
试试这个:
Response='
"count": 1,
"items": [{
"oid": "xyzxyzxyzxyzxyzxyzxyz",
"creationDate": "2019-02-05T02:21:08.662+0000"