Validating if a JSON object is present in a file with nlohmann JSON C++ library


I have a project where I import JSON files to setup global variables. There are various possibilities to the JSON object names in the files, so I want to know how can I check if an object is there or not. The way I tried to do it (with an if statement as shown below) causes an error

The program '..\..\build\jacky.exe' has exited with code 3 (0x00000003).

So it does not work at all. Is there a way to do this? Thanks!

#include <iostream>
#include <string>
#include <fstream>
#include "json.hpp" // json library by nlohmann

std::ifstream gJsonFile;
nlohmann::json j;
int var;

int main(int argc, char *argv[])
{* whatever json file path */, std::ifstream::in); 

    if (gJsonFile.is_open())
        j << gJsonFile;

        if (j["Shirt Size"])  // causes exit with code 3 if false
            var = (j["Shirt Size"]);
            var = (j["AB Circumference"]);
asked on Stack Overflow Jul 21, 2020 by JCSB

1 Answer

if ( j.find("Shirt Size") != j.end() )

Or (this will create an entry if it does not already exist)

if ( !j["Shirt Size"].is_null() )
answered on Stack Overflow Jul 21, 2020 by ChrisMM

User contributions licensed under CC BY-SA 3.0