Home > database >  Access element from nlohmann::json?
Access element from nlohmann::json?

Time:11-26

I want to access element from a json which is the response from one query.

The json structure is :

  json =   { "result": {
            "12CUDzb3oe8RBQ4tYGqsuPsCbsVE4KWfktXRihXf8Ggq": [
                20964,
                347474,
                347475
            ],
            "12ashmTiFStQ8RGUpi1BTCinJakVyDKWjRL6SWhnbxbT": [
                1992,
                1993,
                109096  
            ],
    }}

I want to get the 1st element(result[0]) key from result object ie 12CUDzb3oe8RBQ4tYGqsuPsCbsVE4KWfktXRihXf8Ggq in some variable a and the corresponding array ie [20964, 347474,347475 ] in some varible b.

The problem I am having is that 1st element key value in this case "12CUDzb3oe8RBQ4tYGqsuPsCbsVE4KWfktXRihXf8Ggq" always changes for every query!

Can someone show me the way how can I access it correctly?

CodePudding user response:

json.begin() will give you an iterator pointing to the first element. Then you can access its' key and value using:

auto key = json.begin().key();
auto value = json.begin().value();
  • Related