Search code examples
c++c++11nlohmann-json

How to convert nlohmann json to uint8_t array?


I would like convert my created json object to array of uint8_t[1000]. I tried something like this:

    nlohmann::json j_file;
    j_file["number"] = 2;
    j_file["example"] = "dog";

    uint8_t parsed_json[1000] ={0};
    auto str = j_file.dump();
    std::vector<std::uint8_t> v (str.begin(), str.end());
    std::copy(v.begin(), v.end(), parsed_json);

but is there an easier way to convert json to uint8_t array?


Solution

  • You can copy contents of std::string to the array without using std::vector as proxy.

        uint8_t parsed_json[1000] ={0};
        auto str = j_file.dump();
        std::copy(str.begin(), str.end(), parsed_json);