How to get value type from string using nlohmann json?

Viewed 3040

string I get

{
    "players": [
        {
            "SteamId": "765611974898245625",
            "CommunityBanned": false,
            "VACBanned": true,
            "NumberOfVACBans": 1,
            "DaysSinceLastBan": 1011,
            "NumberOfGameBans": 1,
            "EconomyBan": "none"
        }
    ]
}

I need to get from it

bool VACBanned = true;
int NumberOfVACBans = 1;

and so on

I use nlohmann json

using json = nlohmann::json;
auto j3 = json::parse(respone.c_str());

if (j3.is_boolean()) // crashing without this check
    g_Player[index].bVACBanned = j3.at("VACBanned").get<bool>();

for some reason it doesn't work

1 Answers

I've not used that parser before, just read its readme.md. It appears that both of these methods work:

bool b1 = j3.at("players")[0].at("VACBanned");
bool b2 = j3["players"][0]["CommunityBanned"];

Your JSON has one root node players that is an array; its first element is accessible by [0]; from that point you can access all parsed elements.

Add error checking per your tolerance level :)

P.S. This is just a syntax demo; I assume that OP can get the size of parsed array and iterate through it to get details on each player.

Also, to answer your "for some reason it doesn't work":

g_Player[index].bVACBanned = j3.at("VACBanned").get<bool>();

j3 doesn't have an element "VACBanned", so at("VACBanned") likely returns nullptr that you dereferenced.

Related