![]() |
博学的山寨机 · 将varchar列转换为日期的sql· 1 年前 · |
![]() |
仗义的烈酒 · Convert JavaScript to ...· 1 年前 · |
![]() |
打酱油的莴苣 · 可用性组租用运行状况检查超时 - SQL ...· 1 年前 · |
![]() |
痴情的橙子 · azureml.core.dataset.D ...· 1 年前 · |
![]() |
活泼的高山 · 东声智能创始人韩旭:利用多维度数据融合技术提 ...· 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"
![]() |
博学的山寨机 · 将varchar列转换为日期的sql 1 年前 |