Art Vandelay
Art Vandelay

Reputation: 183

Accessing JSON values in C++

I am trying to write a program that navigates your local disc in Unreal Engine for a small application. I have put together a REST server using Gradle, and long story short, I am given a JSON with a machines directories. I want to pull out the specific directories names, to be returned as string (FText specifically, but that not too important here) array.

I found a library created by nLohmann on github (https://github.com/nlohmann/json) which seems to be the best way to handle a JSON in c++. For the life of me, however, I can't figure out how to pull the directory names out. I've tried an iterator and a straightforward .value() call.

The code and a JSON example are below, any insight would be greatly appreciated.

char buffer[1024];

FILE *lsofFile_p = _popen("py C:\\Users\\jinx5\\CWorkspace\\sysCalls\\PullRoots.py", "r");
fgets(buffer, sizeof(buffer), lsofFile_p);
_pclose(lsofFile_p);

std::string rootsJson(buffer);
string s = rootsJson.substr(1);
s = ReplaceAll(s, "'", "");

//here my string s will contain: [{"description":"Local Disk","name":"C:\\"},{"description":"Local Disk","name":"D:\\"},{"description":"CD Drive","name":"E:\\"}]


//These are two syntax examples I found un nlohmann's docs, neither seems to work 
auto j = json::parse(s);
string descr = j.value("description", "err");

Upvotes: 1

Views: 3468

Answers (1)

Bertrand Martel
Bertrand Martel

Reputation: 45473

I think your problem comes from number of \ in your literal string. You need 5 \ for C:\\ : C:\\\\\.

Here is a working example :

#include "json.hpp"
#include <string>

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

int main(){

    json j = json::parse("[{\"description\":\"Local Disk\",\"name\":\"C:\\\\\"},{\"description\":\"Local Disk\",\"name\":\"D:\\\\\"},{\"description\":\"CD Drive\",\"name\":\"E:\\\\\"}]");

    cout << j.is_array() << endl;

    for (auto& element : j) {
      std::cout << "description : " << element["description"] << " | " << " name : "  << element["name"] << '\n';
    }
    return 0;
}

Upvotes: 3

Related Questions