c++ JsonCpp parse string with escaped quotes as array - c++

I've got the following json string:
{
"data" :
[
{
"cart" : "[{\"name\":\"Test item 1\",\"price\":15,\"quantity\":1,\"sum\":15,\"tax\":\"none\",\"payment_type\":\"advance\",\"item_type\":\"service\"},{\"name\":\"Test item 2\",\"price\":13.01,\"quantity\":2,\"sum\":26.02,\"tax\":\"none\",\"payment_type\":\"part_prepay\",\"item_type\":\"work\"}]",
"contact" : "noname#google.com",
"p_id" : "603",
"sum" : "100.02",
"tax_system" : "osn"
}
],
"msg" : null,
"result" : "success"
}
I can parse cart as std::string after parsing input json string as stringstream:
const std::string ParseJsonData(std::stringstream ssJsonStream)
{
Json::Value jsonData;
Json::Value responseData;
Json::Value responseDataCart;
Json::CharReaderBuilder jsonReader;
std::string errs;
if (Json::parseFromStream(jsonReader, ssJsonStream, &jsonData, &errs)) {
responseData = jsonData["data"];
responseDataCart = responseData[0]["cart"];
return responseDataCart.toStyledString().c_str();
}
else
return "Could not parse HTTP data as JSON";
}
Please, tell me, how can i parse cart as array with JsonCpp?

The same way you parsed the outer JSON!
You started with a string (well, hidden by a stream) and turned it into JSON.
Now that JSON contains a property that is a string and, itself, contains JSON. The problem is recursive. The fact that the inner string originally came from JSON too can be ignored. Just pretend it's a string you typed in.
So, you can use JSON::Reader to in turn get the JSON out of that string.
Something like:
const std::string responseDataCartStr = responseData[0]["cart"].asString();
Json::Reader reader;
if (!reader.parse(responseDataCartStr, responseDataCart))
throw std::runtime_error("Parsing nested JSON failed");
JsonCpp provides a few ways to parse JSON and it's worth exploring them to find the most appropriate for your use case. The above is just an example.
Ignore the backslashes — the escaping was meaningful within the encapsulating JSON document, but the outermost parse stage should already have taken that into consideration. You'll see if you print responseDataCartStr to console that it is a valid JSON document in its own right.

Related

bsonxx::from_json convert all value types to string

I am using Boost's Property Tree library for storing my json files. For example,
I have the following JSON file:
{
"var" : true,
"bar" : -1.56
}
Next I parse this file to ptree object, do my job and want to store output in MongoDB. For this I convert it back to JSON string:
boost::property_tree::ptree root;
boost::property_tree::read_json(file_path, root);
... // do my job
std::stringstream ss;
boost::property_tree::json_parser::write_json(ss, root);
std::string my_json_string = ss.str();
After this I push my results to MongoDB, by converting JSON string to BSON like this: bsonxx::from_json(my_json_string). As result I receive the following entity in database:
{
"var" : "true",
"bar" : "-1.56"
}
Is there a way to insert my JSON string to MongoDB with persistence types?

How to create empty json object correctly using web.json in cpp?

I want to create following json request:
{
"Value1":{},
"Value2":"some string value"
}
to achieve this I have tried following code in cpp:
json::value &refRequest
json::value jRequest = json::value();
refRequest[requestKey::Value1] = json::value(json::value::object()); //for creating empty object
refRequest[requestKey::Value2] = json::value::string("some string");
but it gives output as:
{
"Value1":},
"Value2":"some string value"
}
if you observe, instead of returning empty object as {} it gives the output as } and this results in to malformed request. I am not sure where exactly I am going wrong, any help will would be appreciated. Thanks
I believe your mistake is that you are constructing a json::value from a json::value::object()
According to the documentation the line should be fixed to:
refRequest[requestKey::Value1] = json::value::object();

Not able to get values from JSON in Casablanca, C++

I'm using Casablanca, cpprestsdk to consume REST APIs in C++, in Visual Studio 2015 Professional. I'm trying to develop a simple example here hitting an API and parsing the response as JSON. The URL I'm using, actually returns all the parameters sent to the API.
I've hit the API and got response as well, extracted json from the response successfully. But when i try to read a value at any key from json, it crashes. Hence i put a check whether that key is available or not, and it always says json does not have the field. As an example i printed the data i.e. json. It has the key/field "name" but when i check it via has_field, it returns false.
Please help.
Complete code is below :
json::value postData;
postData[L"name"] = json::value::string(L"Joe Smith");
postData[L"sport"] = json::value::string(L"Baseball");
http_client client(L"https://httpbin.org/post);
http_request request(methods::POST);
request.set_body(postData);
client.request(request).then([](web::http::http_response response) {
json::value j = response.extract_json().get();
json::value data = j.at(U("data"));
std::wcout << "Json : " << data;
// Prints "{\"name\":\"Joe Smith\",\"sport\":\"Baseball\"}"
if (data.has_field(U("name"))) {
std::cout << "Name Found";
}
else {
std::cout << "Name key not Found";
}
});
It seems that your response looks like this:
{ "data": "{\"name\":\"Joe Smith\",\"sport\":\"Baseball\"}" }`
i.e. the actual data is not a JSon object but escaped JSon passed as string. I guess you need to return a payload that looks like this to do what you want to do the way you are doing it:
{
"data": {
"name": "John Smith",
"sport": "Baseball"
}
}

Rapidjson parse another json if first one has errors

Say I have a JSON string and it has an error and thus can not be parsed. Then I want to parse another JSON string, which will replace the original one. I want to do that using the same rapidjson::Document as eventually I need to have parsed the valid JSON in that document.
So:
rapidjson::Document document;
if (document.Parse<0>("{ \"hello\" : \"wor........ ").HasParseError())
{
// How to parse the correct json "{ \"hello\" : \"world\" }" here
// using the same `Document` ?
}
Should I just write
if (document.Parse<0>("{ \"hello\" : \"wor........ ").HasParseError())
{
document.Parse<0>("{ \"hello\" : \"world\" }");
}
Yes, if first parsing hes error then parsing another JSON by using the same document is OK, as far as it clears that data and parses newly.

Json regex deserialization with JSON.Net

I'm trying to read the following example json from a text file into a string using the JSON.Net parsing library.
Content of C:\temp\regeLib.json
{
"Regular Expressions Library":
{
"SampleRegex":"^(?<FIELD1>\d+)_(?<FIELD2>\d+)_(?<FIELD3>[\w\&-]+)_(?<FIELD4>\w+).txt$"
}
}
Example code to try and parse:
Newtonsoft.Json.Converters.RegexConverter rConv = new Newtonsoft.Json.Converters.RegexConverter();
using (StreamReader reader = File.OpenText(libPath))
{
string foo = reader.ReadToEnd();
JObject jo = JObject.Parse(foo);//<--ERROR
//How to use RegexConverter to parse??
Newtonsoft.Json.JsonTextReader jtr = new Newtonsoft.Json.JsonTextReader(reader);
JObject test = rConv.ReadJson(jtr);//<--Not sure what parameters to provide
string sampleRegex = test.ToString();
}
It seems I need to use the converter, I know the code above is wrong, but I can't find any examples that describe how / if this can be done. Is it possible to read a regular expression token from a text file to a string using JSON.Net? Any help is appreciated.
UPDATE:
Played with it more and figured out I had to escape the character classes, once I made the correction below I was able to parse to a JObject and use LINQ to query for the regex pattern.
Corrected content C:\temp\regeLib.json
{
"Regular Expressions Library":
{
"SampleRegex":"^(?<FIELD1>\\d+)_(?<FIELD2>\\d+)_(?<FIELD3>[\\w\\&-]+)_(?<FIELD4>\\w+).txt$"
}
}
Corrected code
using (StreamReader reader = File.OpenText(libPath))
{
string content = reader.ReadToEnd().Trim();
JObject regexLib = JObject.Parse(content);
string sampleRegex = regexLib["Regular Expressions Library"]["SampleRegex"].ToString();
//Which then lets me do the following...
Regex rSampleRegex = new Regex(sampleRegex);
foreach (string sampleFilePath in Directory.GetFiles(dirSampleFiles, "*"))
{
filename = Path.GetFileName(sampleFilePath);
if (rSampleRegex.IsMatch(filename))
{
//Do stuff...
}
}
}
Not sure if this is the best approach, but it seems to work for my case.
i don't understand why you have to store such a small regex in a json file, are you going to expand the regex in the future?
if so, rather than doing this
JObject regexLib = JObject.Parse(content);
string sampleRegex = regexLib["Regular Expressions Library"]["SampleRegex"].ToString();
Consider using json2csharp to make classes, at least it's strongly-typed and make it more maintainable.
I think a more appropriate json would look like this (assumptions):
{
"Regular Expressions Library": [
{
"SampleRegex": "^(?<FIELD1>\\d+)_(?<FIELD2>\\d+)_(?<FIELD3>[\\w\\&-]+)_(?<FIELD4>\\w+).txt$"
},
{
"SampleRegex2": "^(?<FIELD1>\\d+)_(?<FIELD2>\\d+)_(?<FIELD3>[\\w\\&-]+)_(?<FIELD4>\\w+).txt$"
}
]
}
It would make more sense this way to store a regex in a "settings" file