How to read json file using rapidjson and output to std::string?

waas1919 picture waas1919 · Jul 22, 2017 · Viewed 8.9k times · Source

How can I read a *.json file and put the output on a std::string?

I have this sample, but I always get null on std::string.

#include <rapidjson/document.h>
#include <rapidjson/istreamwrapper.h>
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <rapidjson/ostreamwrapper.h>
#include <fstream>
#include <iostream>

using namespace rapidjson;
using namespace std;

void main()
{
    ifstream ifs("input.json");
    IStreamWrapper isw(ifs);
    Document d;
    d.ParseStream(isw);

    StringBuffer buffer;
    Writer<StringBuffer> writer(buffer);
    d.Accept(writer);

    std::string jsonStr(buffer.GetString());
    if(jsonStr == "null")
        std::cout << "is null..." << std::endl; //<--always here!
    else
    {
        std::cout << jsonStr.c_str() << std::endl;

        d["ip"] = "123456789";

        ofstream ofs("output.json");
        OStreamWrapper osw(ofs);
        Writer<OStreamWrapper> writer2(osw);
        d.Accept(writer2);
    }
}

This is my json file:

{
  "ip" :  "192.168.0.100",
  "angle x": 20,
  "angle y": 0,
  "angle z": 0
}

Answer

Azeem picture Azeem · Jul 22, 2017

You need to check for all the errors before converting to std::string. Make sure that the file is open for reading / writing and the parsing is successful i.e. the JSON is valid. GetParseError() and GetErrorOffset() are the functions to validate parsing.

I've used your example and enhanced it. Hope you won't mind. :-)

Here's a working example:

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <rapidjson/document.h>
#include <rapidjson/istreamwrapper.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/ostreamwrapper.h>

int main()
{
    using namespace rapidjson;

    std::ifstream ifs { R"(C:\Test\Test.json)" };
    if ( !ifs.is_open() )
    {
        std::cerr << "Could not open file for reading!\n";
        return EXIT_FAILURE;
    }

    IStreamWrapper isw { ifs };

    Document doc {};
    doc.ParseStream( isw );

    StringBuffer buffer {};
    Writer<StringBuffer> writer { buffer };
    doc.Accept( writer );

    if ( doc.HasParseError() )
    {
        std::cout << "Error  : " << doc.GetParseError()  << '\n'
                  << "Offset : " << doc.GetErrorOffset() << '\n';
        return EXIT_FAILURE;
    }

    const std::string jsonStr { buffer.GetString() };

    std::cout << jsonStr << '\n';

    doc[ "ip" ] = "127.0.0.1";

    std::ofstream ofs { R"(C:\Test\NewTest.json)" };
    if ( !ofs.is_open() )
    {
        std::cerr << "Could not open file for writing!\n";
        return EXIT_FAILURE;
    }

    OStreamWrapper osw { ofs };
    Writer<OStreamWrapper> writer2 { osw };
    doc.Accept( writer2 );

    return EXIT_SUCCESS;
}