Home > Enterprise >  regex to parse json content as a string in c
regex to parse json content as a string in c

Time:08-04

My application receives a JSON response from a server and sometimes the JSON response has format issues. so I would like to parse this JSON response as a string. Below is the sample JSON response I'm dealing with.

[{
"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)

, 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)

        std::regex _regex("{", "}");
        std::smatch match;
        while (std::regex_search(GetScanReportURL_Res, match, _regex))
        {
            std::cout << match.str(0);
        }

CodePudding user response:

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. But perhaps your data is sufficiently restricted that it can at least sort of work anyway.

  • Related