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
?
6 Answers
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);

- 2,976
- 4
- 22
- 38
-
9Although this works great, the current version of JsonCPP says Json::FastWriter has been deprecated in favor of Json::StreamWriterBuilder. But the functionality of writing to a string was removed, and now it is necessary to write to a std::stringstream. Can you elaborate on that? – nico Nov 13 '17 at 22:21
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?

- 7,828
- 3
- 35
- 46
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
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

- 25,920
- 39
- 129
- 186
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.

- 479
- 9
- 16
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;
}