Skip to content

JSON Pretty Print

gchudnov edited this page Dec 21, 2014 · 6 revisions

To pretty-print JSON, read it to json_value object and save to the output stream with format() manipulator.

Code:

#include <string>
#include <sstream>
#include <cpp-json-qi/json.h>

  std::string input("....")
  std::istringstream iss(input);
  jsonqi::json_value val;
  iss >> val;

  std::ostringstream oss;
  oss << jsonqi::format() << jsonqi::json_value(val);

input JSON:

{"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } }}

output JSON:

{
  "menu": {
    "id": "file",
    "popup": {
      "menuitem": [
        {
          "onclick": "CreateNewDoc()",
          "value": "New"
        },
        {
          "onclick": "OpenDoc()",
          "value": "Open"
        },
        {
          "onclick": "CloseDoc()",
          "value": "Close"
        }
      ]
    },
    "value": "File"
  }
}

Clone this wiki locally