c++jsonjson-spirit

Pretty-printing with JSON Spirit


My C++ program receives a long (thousands of symbols) JSON string, which I'd like to print using JSON Spirit (for debugging) with multiple lines, right indentation etc. For example:

{
  "abc": "def",
  "xyz":
  [
    "pqr": "ijk"
  ]
}

and so on. I tried the write function:

const json_spirit::Value val("...long JSON string here ...");
cout << json_spirit::write(val, json_spirit::pretty_print) << endl;

but got only additional backslashes in the original string.

Can you please advise how to do that?


Solution

  • The reason you're getting your original input string back is because you assign the string directly to a json_spirit::Value. What you need to do instead is have json_spirit parse the string.

    The C++11 code below gives the expected output:

    #include <json_spirit/json_spirit.h>
    #include <ostream>
    #include <string>
    
    int main() {
      std::string const inputStr = 
        R"raw({ "abc": "def", "xyz": [ "pqr": "ijk" ] })raw";
    
      json_spirit::Value inputParsed;
      json_spirit::read(inputStr, inputParsed);
    
      std::cout 
        << json_spirit::write(inputParsed, json_spirit::pretty_print) << "\n";
    }
    

    Side note: There's a whole bunch of more lightweight C++ JSON libraries (i.e. not requiring Boost), in case that should interest you. I've personally used nlohmann's json which requires only a single header file. RapidJSON seems to be an excellent option as well. Tons of benchmarks for 40+ C++ JSON libraries can be found on the nativejson-benchmark page.