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

How to deserialize arrays from json #1681

Closed
WhoseTheNerd opened this issue Jul 22, 2019 · 3 comments
Closed

How to deserialize arrays from json #1681

WhoseTheNerd opened this issue Jul 22, 2019 · 3 comments
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@WhoseTheNerd
Copy link

  • Describe what you want to achieve.
    I want to get std::vectors from json
{
  "vertices": [
    3.227124,
    ...
  ],
  "textureCoords": [
     0.863038,
     ...
  ],
  ...
}
  • Describe what you tried.
    I tried code below, and got confused what j.get() does or works, since there is no wiki on this repo
auto j = json::parse(json);
std::vector<float> positions;
positions = j["vertices"];
  • Describe which system (OS, compiler) you are using.
    Ubuntu 18.04 LTS
$ gcc --version
gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  • Describe which version of the library you are using (release version, develop branch).
    develop branch by just putting it into the project.
@nlohmann
Copy link
Owner

This code works:

#include "json.hpp"

using json = nlohmann::json;

int main()
{
    json j;
    j["vertices"] = {3.227124, 1.1, 2.2, 3.3, 4.4};
    
    std::vector<float> positions;
    j["vertices"].get_to(positions);
}

@Faaux
Copy link

Faaux commented Jul 24, 2019

Is it by design that get_to appends to the vector? Wondering since you are reserving in json.hpp like this:
arr.reserve(j.size()); without considering the size the std::vector already has.

Repro:

nlohmann::json j;
j["vertices"] = {1.0};

std::vector<float> positions = {2.0};
j["vertices"].get_to(positions);

assert(positions.size() == 2)

which means the reserve call should take the current size into account.

@WhoseTheNerd
Copy link
Author

Thank you, that code worked fine. Closing an issue.

@nlohmann nlohmann added the solution: proposed fix a fix for the issue has been proposed and waits for confirmation label Jul 28, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation
Projects
None yet
Development

No branches or pull requests

3 participants