Skip to content

Access random objects in json #2820

Answered by nlohmann
mementoseeds asked this question in Q&A
Discussion options

You must be logged in to vote

You can do it like explained in https://www.techiedelight.com/get-random-value-stl-containers-cpp/:

Example:

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

using json = nlohmann::json;

const json& get_random(const json& j)
{
    auto it = j.cbegin();
    int random = rand() % j.size();
    std::advance(it, random);
 
    return *it;
}

int main()
{
    json val = R"(
    {
        "item1": "value1",
        "item2": "value2",
        "item3": "value3"
    }
    )"_json;
    
    std::cout << get_random(val) << std::endl;
    std::cout << get_random(val) << std::endl;
    std::cout << get_random(val) << std::endl;
}

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@mementoseeds
Comment options

@gregmarr
Comment options

Answer selected by mementoseeds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants