[英]regex to parse json content as a string in c++
My application receives a JSON response from a server and sometimes the JSON response has format issues.我的应用程序收到来自服务器的 JSON 响应,有时 JSON 响应存在格式问题。 so I would like to parse this JSON response as a string.
所以我想将此 JSON 响应解析为字符串。 Below is the sample JSON response I'm dealing with.
下面是我正在处理的示例 JSON 响应。
[{
"Id": "0000001",
"fName": "ABCD",
"lName": "ZY",
"salary": 1000
},
{
"Id": "0000002",
"fName": "EFGH",
"lName": "XW",
"salary": 1010
},
{
"Id": "0000003",
"fName": "IJKL",
"lName": "VU",
"salary": 1020
}]
I want to get the content between the braces into multiple vectors.我想将大括号之间的内容放入多个向量中。 so that I can easily iterate and parse the data.
这样我就可以轻松地迭代和解析数据。 I tried using
我尝试使用
str.substr(first, last - first)
str.substr(第一,最后 - 第一)
, but this will return only one string where I need all possible matches. ,但这只会返回一个字符串,我需要所有可能的匹配项。 And I tried using regex as below and it is throwing below exception.
我尝试使用下面的正则表达式,它抛出异常。 Please help me!
请帮我!
(regex_error(error_badrepeat): One of *?+{ was not preceded by a valid regular expression)
(regex_error(error_badrepeat): *?+{ 之一前面没有有效的正则表达式)
std::regex _regex("{", "}");
std::smatch match;
while (std::regex_search(GetScanReportURL_Res, match, _regex))
{
std::cout << match.str(0);
}
I'm not quite sure how your code is even compiling (I think it must be trying to treat the "{"
and "}"
as iterators), but your regex is pretty clearly broken.我不太确定你的代码是如何编译的(我认为它必须试图将
"{"
和"}"
视为迭代器),但你的正则表达式很明显被破坏了。 I'd use something like this:我会使用这样的东西:
#include <string>
#include <regex>
#include <iostream>
std::string input = R"([{
"Id": "0000001",
"fName": "ABCD",
"lName": "ZY",
"salary": 1000
},
{
"Id": "0000002",
"fName": "EFGH",
"lName": "XW",
"salary": 1010
},
{
"Id": "0000003",
"fName": "IJKL",
"lName": "VU",
"salary": 1020
}])";
int main() {
std::regex r("\\{[^}]*\\}");
std::smatch result;
while (std::regex_search(input, result, r)) {
std::cout << result.str() << "\n\n-----\n\n";
input = result.suffix();
}
}
I'd add, however, the proviso that just about any regex-based attempt at this is basically broken.但是,我要补充一点,任何基于正则表达式的尝试基本上都被破坏了。 If one of the strings contains a
}
, this will treat that as the end of the JSON object, whereas it should basically ignore it, only looking for a }
that's outside any string.如果其中一个字符串包含
}
,这会将其视为 JSON object 的结尾,而它基本上应该忽略它,只寻找任何字符串之外的}
。 But perhaps your data is sufficiently restricted that it can at least sort of work anyway.但也许您的数据受到了足够的限制,以至于它至少可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.