ajayramesh
ajayramesh

Reputation: 3784

How to read JSON content as it is in C++?

I am trying read a text file which has Valid JSON content but not string. The below code works fine if it is a string dump. For example - if file contents are like this "{ \"happy\": true, \"pi\": 3.141 }" then it will parse without errors. Now I want to find out a way which minimizes these conversion ? How to convert JSON content to String dump in C++ using any standard lib? I am using nlohmann for now, but seems like this requires additional coding. Please educate me if I can hack this with simple code.

My Code

#include <iostream>
#include <fstream>
#include <streambuf>
#include <nlohmann/json.hpp>

using namespace std;
using json = nlohmann::json;

int main()
{
    std::fstream f_json("C://json.txt");

    json jFile;
    try {
        jFile = json::parse(f_json);
    }
    catch (json::parse_error &e)
    {
        std::cerr << e.what() << std::endl;
    }
    return 0;
}

Our client produces JSON files which is like below.

{
    "happy": true,
    "pi": 3.141
  }

Upvotes: 0

Views: 865

Answers (2)

Loki Astari
Loki Astari

Reputation: 264431

I like to use ThorsSerializer. Disclaimer I wrote it.

#include "ThorSerialize/JsonThor.h"
#include "ThorSerialize/SerUtil.h"
#include <sstream>
#include <iostream>
#include <string>

struct MyObj
{
    bool        happy;
    double      pi;
};
ThorsAnvil_MakeTrait(MyObj, happy, pi);

Example Usage:

int main()
{
    using ThorsAnvil::Serialize::jsonImport;
    using ThorsAnvil::Serialize::jsonExport;

    std::stringstream file(R"({ "happy": true, "pi": 3.141 })");

    MyObj   data;
    file >> jsonImport(data);


    std::cout << jsonExport(data) << "\n";
}

Output:

{
    "happy": true,
    "pi": 3.141
}

It works the same for a file stream. But you should not escape the " characters in the file.

Upvotes: 1

ajayramesh
ajayramesh

Reputation: 3784

My file is under C:/test.json, so it dint had the permission to open it. Now I placed it in proper folder. Now its working fine.

Upvotes: 1

Related Questions