0

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);
        }
1
  • "fName": "{}," is going to ruin your day though. Commented Aug 3, 2022 at 18:28

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.