BRabbit27
BRabbit27

Reputation: 6623

Converting a Json::Value to std::string?

I am using JsonCpp to build a JSON object. Once the object is built, is there a way I can get the object as an std::string?

Upvotes: 57

Views: 97169

Answers (6)

Matias Kinnunen
Matias Kinnunen

Reputation: 8540

Json::Writer is deprecated. Use Json::StreamWriter or Json::StreamWriterBuilder instead.

Json::writeString writes into a stringstream and then returns a string:

Json::Value json = ...;
Json::StreamWriterBuilder builder;
builder["indentation"] = ""; // If you want whitespace-less output
const std::string output = Json::writeString(builder, json);

Kudos to cdunn2001's answer here: How to get JsonCPP values as strings?

Upvotes: 37

user1100264
user1100264

Reputation:

This little helper might do.

//////////////////////////////////////////////////
// json.asString()
//
std::string JsonAsString(const Json::Value &json)
{
    std::string result;
    Json::StreamWriterBuilder wbuilder;

    wbuilder["indentation"] = "";       // Optional
    result = Json::writeString(wbuilder, json);
    return result;
}

Upvotes: 1

Kokeb
Kokeb

Reputation: 437

You can also use the method toStyledString().

jsonValue.toStyledString();

The method "toStyledString()" converts any value to a formatted string. See also the link: doc for toStyledString

Upvotes: 21

In my context, I instead used a simple .asString() at the end of my json value object. As @Searene said, it gets rid of the extra quotes that you don't necessary wants if you want to process it after.

Json::Value credentials;
Json::Reader reader;

// Catch the error if wanted for the reader if wanted. 
reader.parse(request.body(), credentials);

std::string usager, password;
usager = credentials["usager"].asString();
password = credentials["password"].asString();

If the value is a int instead of a string, .asInt() works great as well.

Upvotes: 1

Searene
Searene

Reputation: 27574

If your Json::value is of string type, e.g. "bar" in the following json

{
    "foo": "bar"
}

You can use Json::Value.asString to get the value of bar without extra quotes(which will be added if you use StringWriterBuilder). Here is an example:

Json::Value rootJsonValue;
rootJsonValue["foo"] = "bar";
std::string s = rootJsonValue["foo"].asString();
std::cout << s << std::endl; // bar

Upvotes: 5

Jordan Doyle
Jordan Doyle

Reputation: 3026

You can use a Json::Writer to do exactly this, since I assume you want to save it somewhere so you don't want human readable output, your best bet would be to use a Json::FastWriter and then you can call the write method with the parameter of your Json::Value (ie. your root) and then that simply returns a std::string like so:

Json::FastWriter fastWriter;
std::string output = fastWriter.write(root);

Upvotes: 55

Related Questions