Access random objects in json #2820
-
Hi, I want to implement a feature in one of my projects which requires being able to select a specific amount of randomly selected items from a json object. For example, let's say I have this json document
and I want to select 2 random keys from it. Then the selected keys could be "item1" and "item2", or "item1" and "item3", or "item2" and "item3". Is it possible to do that? Alternatively, is it possible to access json objects through an index? For example with the above document, json[0] could return the key "item1". But if the document were reordered like this
then json[0] would return "item2". One way or another, I wish to be able to select a specific amount of objects from a json document chosen at random - either through a built in function or through a number index where the number is randomly generated. Is any of this possible? Thanks in advance. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
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;
} |
Beta Was this translation helpful? Give feedback.
You can do it like explained in https://www.techiedelight.com/get-random-value-stl-containers-cpp/:
Example: