![]() |
寂寞的伏特加 · 瀛����������痉���椋�缓璁句�椤 ...· 9 月前 · |
![]() |
暗恋学妹的消炎药 · 中国人民武装警察部队,历史上有过哪些体制调整 ...· 10 月前 · |
![]() |
礼貌的跑步机 · 第十二届石壁客家论坛举行_ 文旅经济_福 ...· 11 月前 · |
![]() |
俊秀的小狗 · kindle的KU会员值不值得买? - 知乎· 1 年前 · |
![]() |
性感的大象 · 骑士3.0 NQI价格报价行情 - 京东· 1 年前 · |
我希望在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"
![]() |
寂寞的伏特加 · 瀛����������痉���椋�缓璁句�椤规不��伐浣�����缃叉����寤��寤鸿�涓��浼����浣�����瀛��淇℃�涓��锛��涔��锛�/title> <meta name= 9 月前 |
![]() |
礼貌的跑步机 · 第十二届石壁客家论坛举行_ 文旅经济_福建省人民政府门户网站 11 月前 |
![]() |
俊秀的小狗 · kindle的KU会员值不值得买? - 知乎 1 年前 |
![]() |
性感的大象 · 骑士3.0 NQI价格报价行情 - 京东 1 年前 |