0

I have a json object in c++. I am using json_cpp library.

I want to get the string from the Json::Value object. I am using it like below.

Json::Value obj;
....
....
....
string str = obj.toStyledString();

This returns the string in the pretty print format. But I want the string without any indentation. How can I do that as there are no other functions provided in the class?

4
  • JSON is a character string, normally transmitted without format information. Any representation as "obj" is not "JSON" but rather a translation of the JSON into the elements of some kit. Commented Sep 20, 2013 at 20:22
  • Hint: What operation created "obj"? Is there a reverse operation? Commented Sep 20, 2013 at 20:32
  • I suppose that toStyledString() is actually a reverse operation :) But it returnes a formatted JSON string while the topic starter wants an unformatted. Commented Sep 20, 2013 at 21:02
  • @FreeNickname - I was trying to prompt the OP to actually look at the documentation. Commented Sep 20, 2013 at 21:36

2 Answers 2

3

You could use Json::FastWriter it does not have any indentation and formatting since it outputs everything on a single line. it is normally not suitable for 'human' consumption.

std::string toUnStyledString(const Json::Value& value)
{
   Json::FastWriter writer;
   return writer.write( value );
}

The function toStyledString also simply uses a Json::StyledWriter if you look into the definition of Json::Value::toStyledString.

Sign up to request clarification or add additional context in comments.

Comments

0

Well, if this library doesn't provide appropriate methods then you could write them yourself. The JSON format is rather simple, so I don't think that it will take a lot of work. Here you can find a good graphical representation of JSON format:

http://json.org

P.S. I've never worked with this particular library, so I propose sort of a general solution.

UPDATE: another option is to get a string returned by toStyledString() and remove indentation. But it requires string processing and will probably be resource consuming. Note that you can't just remove tabs/spaces/new line symbols, because they can be a part of JSON object. Why do you want unindented string again?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.