4

I'm using https://github.com/nlohmann/json to load JSON file into my program.
At this moment, I'm loading it:

json jsonFile;
ifstream ifs("data/test.json");
ifs >> jsonFile;

// create JSON from stream
json j_complete(jsonFile);

And I have access to it via:

jsonFile["data"][X][Y] // X, Y are indexes

But I want to create vector from this - how can I do this?
Here is sample of this file:

{
    "cols": [
        "id",
        "title",
        "quantity",
        "price"
    ],
    "data": [
        [
            12,
            "Guzman",
            6,
            "6.31"
        ],
        [
            2,
            "..",
            5,
            "4.34"
        ],
        [
            3,
            "Goldeniererere",
            14,
            "4.15"
        ]
    ]
}
Vertisan
  • 720
  • 3
  • 14
  • 34

1 Answers1

1

The json parser has overloaded the [] operator to accept an integer for a JSON array. So it's accessed in the same way as a vector, but the underlying data structure doesn't have much in common. So you need to push it back into an std:::vector. You'll also want to convert the fields from JSON to something more C++ like if you want to use the data elsewhere. Something like {int id, std::string title, int quantity, float price};

Then you will have it as flat C++ list of structures in memory with a thin std::vector wrapper over it.

Malcolm McLean
  • 6,258
  • 1
  • 17
  • 18