Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json-cpp - how to initialize from string and get string value?

Tags:

My code below crashes(Debug Error! R6010 abort() has been called). Can you help me? I'd also would like to know how to initialize the json object from a string value.

Json::Value obj; obj["test"] = 5; obj["testsd"] = 655; string c = obj.asString(); 
like image 491
Greyshack Avatar asked Jun 29 '15 16:06

Greyshack


People also ask

How do I parse a string in JSON?

Example - Parsing JSONUse the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.

Can JSON be just a string?

JSON is purely a string with a specified data format — it contains only properties, no methods. JSON requires double quotes to be used around strings and property names. Single quotes are not valid other than surrounding the entire JSON string.

Is JSON string the same as string?

No, JSON is not a string. It's a data structure.


2 Answers

Hello it is pretty simple:

1 - You need a CPP JSON value object (Json::Value) to store your data

2 - Use a Json Reader (Json::Reader) to read a JSON String and parse into a JSON Object

3 - Do your Stuff :)

Here is a simple code to make those steps:

#include <stdio.h> #include <jsoncpp/json/json.h> #include <jsoncpp/json/reader.h> #include <jsoncpp/json/writer.h> #include <jsoncpp/json/value.h> #include <string>  int main( int argc, const char* argv[] ) {      std::string strJson = "{\"mykey\" : \"myvalue\"}"; // need escape the quotes      Json::Value root;        Json::Reader reader;     bool parsingSuccessful = reader.parse( strJson.c_str(), root );     //parse process     if ( !parsingSuccessful )     {         std::cout  << "Failed to parse"                << reader.getFormattedErrorMessages();         return 0;     }     std::cout << root.get("mykey", "A Default Value if not exists" ).asString() << std::endl;     return 0; } 

To compile: g++ YourMainFile.cpp -o main -l jsoncpp

I hope it helps ;)

like image 111
Irineu Antunes Avatar answered Oct 15 '22 20:10

Irineu Antunes


Json::Reader is deprecated. Use Json::CharReader and Json::CharReaderBuilder instead:

std::string strJson = R"({"foo": "bar"})";  Json::CharReaderBuilder builder; Json::CharReader* reader = builder.newCharReader();  Json::Value json; std::string errors;  bool parsingSuccessful = reader->parse(     strJson.c_str(),     strJson.c_str() + strJson.size(),     &json,     &errors ); delete reader;  if (!parsingSuccessful) {     std::cout << "Failed to parse the JSON, errors:" << std::endl;     std::cout << errors << std::endl;     return; }  std::cout << json.get("foo", "default value").asString() << std::endl; 

Kudos to p-a-o-l-o for their answer here: Parsing JSON string with jsoncpp

like image 37
Matias Kinnunen Avatar answered Oct 15 '22 20:10

Matias Kinnunen