Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get JsonCPP values as strings?

Tags:

c++

json

jsoncpp

I am parsing json data using JsonCpp. I don't really need to understand the data, i just need to print out some properties and their values out. It somehow is hard to do. First I need to know what type the value is and then get the value and then convert it to string again! There is a styled writer but I don't want to use it as it appends some CRLF at the end.

I do something like this

CJsonHelper::getUInt(Json::Value &root, std::string key){
    return root.get(key, 0-1).isInt() ? root.get(key, 0-1).asUInt() : 0-1;
}

Could I just write a single function to get all the properties with just that function which doesn't really care about the types etc?

like image 751
Lalith Avatar asked Jan 13 '12 01:01

Lalith


People also ask

How do I read a JSON file in CPP?

Here's the code: #include <json/value. h> #include <fstream> std::ifstream people_file("people. json", std::ifstream::binary); people_file >> people; cout<<people; //This will print the entire json object. //The following lines will let you access the indexed objects.

What are JSON keys?

A JSON object contains zero, one, or more key-value pairs, also called properties. The object is surrounded by curly braces {} . Every key-value pair is separated by a comma. The order of the key-value pair is irrelevant. A key-value pair consists of a key and a value, separated by a colon ( : ).

What is JSON format?

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).


2 Answers

The project has moved to GitHub.

To avoid all linefeeds, use a StreamWriterBuilder:

Json::Value whatever = ...;
Json::StreamWriterBuilder builder;
builder.settings_["indentation"] = "";
std::string out = Json::writeString(builder, whatever);
like image 112
cdunn2001 Avatar answered Oct 03 '22 17:10

cdunn2001


You can trivially create your own writer that does whatever you want. Have look at the code for StyledWriter. The CRLF's you don't like come from StyledWriter::Write. You can create your own writer class that doesn't have those CRLF's.

If you don't mind modifying the library, change the writer so that functions like writeValue are protected rather than private. Then you can derive your own class from StyledWriter with a different Write function and still use the various write* functions to do the details of the conversion.

like image 38
David Schwartz Avatar answered Oct 03 '22 16:10

David Schwartz