Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Elegant conversion of a 2-D-json array to a standard C++ array #2805

Closed
DocDriven opened this issue Jun 2, 2021 · 2 comments
Closed

Elegant conversion of a 2-D-json array to a standard C++ array #2805

DocDriven opened this issue Jun 2, 2021 · 2 comments

Comments

@DocDriven
Copy link

DocDriven commented Jun 2, 2021

I have a question regarding the conversion of a json array into a standard C++ array (not a vector!). I have a file that looks basically like this:

{
   "sensors": [
      {
         "id": 10,
         "matrix": [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]
      }
   ],
   "actuators": [
   ]
}

The elements under "matrix" are 2-D-arrays of floats, which are of importance for other parts of the application. I have found a solution to write the matrix field to a variable of type std::vector<std::vector<float>>. The code for that is below:

#include <iostream>
#include <cstdint>
#include <string>
#include <fstream>
#include <vector>

#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main ()
{
    std::string file = "test.json";
    std::ifstream ifs(file);
    json j = json::parse(ifs);

    uint64_t id = 10;

    // empty initialization
    json sensorcfg(json::value_t::object);

    // if the ID is found, retrieve the config
    for (auto it : j["sensors"]) {
        if (it["id"].get<uint64_t>() == id) {
            sensorcfg = it;
            break;
        }
    }

    std::vector<std::vector<float>> m;

    if (!sensorcfg.empty()) {
           m = sensorcfg["matrix"].get<std::vector<std::vector<float>>>();

           for(auto i : m) {
               for(auto j : i) {
                   std::cout << j << std::endl;
               }
           }
   }
}

The problem with this solution is that I must not use vectors when defining m, but a standard C array like m[3][3]. Is there an elegant way to do the conversion? I tried calling get<float[3][3]>(), but this is not working.

I would be grateful for a reply. Thanks!

@nlohmann
Copy link
Owner

nlohmann commented Jun 3, 2021

Unfortunately, C arrays are currently not supported out of the box. To avoid creating a vector first, you could need to iterate sensorcfg["matrix"] yourself and copy the values to the destination array.

@DocDriven
Copy link
Author

Thanks for clarifying. Please consider this issue resolved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants