c++jsonnlohmann-json

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[])
{
    gJsonFile.open(/* 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"]);
        
        else
            var = (j["AB Circumference"]);
        
    }
}

Solution

  • 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() )
    

    Update 2023:

    Note that newer versions of nlohmann::json have a contains method, so you can do

    if ( j.contains("Shirt Size") )
    

    Though, similar to contains in std::map (and others), if you need the value after, use find and store it's iterator to access its value.