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

Problem getting vector (array) of strings #1644

Closed
chakpongchung opened this issue Jun 17, 2019 · 3 comments
Closed

Problem getting vector (array) of strings #1644

chakpongchung opened this issue Jun 17, 2019 · 3 comments
Labels
kind: bug solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@chakpongchung
Copy link

Similar to this one:

#44

#include <nlohmann/json.hpp>
#include <iostream>

using nlohmann::json;

int main() {
  auto j = R"(
    {
         "names": ["Tim", "Tom"],
         "num": [1, 2]
    }
    )"_json;

  std::vector<std::string> names;
  names = j["names"];

  for (auto i : names) {
    std::cout << i << " ";
  }

  // prints: Tim Tom
}

main.cpp:14:20: error: ambiguous overload for ‘operator=’ (operand types are ‘std::vector<std::__cxx11::basic_string >’ and ‘nlohmann::basic_json<>::value_type {aka nlohmann::basic_json<>}’)
names = j["names"];

Hi @nlohmann , separating the definition and declaration doesnt work again. Any solution for this? In some cases this separation is needed.

@nickaein
Copy link
Contributor

nickaein commented Jun 17, 2019

Implicit type conversion from JSON objects is not recommended anymore. You might use explicitly-typed get<T>() method:

names = j["names"].get<std::vector<std::string>>();

or even better, use the below API mentioned by nlohmann which is much more concise.

@nlohmann nlohmann added the solution: proposed fix a fix for the issue has been proposed and waits for confirmation label Jun 22, 2019
@nlohmann
Copy link
Owner

This is a known issue, and there is no real way to fix it while preserving support for implicit conversions. The proposal of @nickaein works, however. You can further simplify the code with get_to (https://nlohmann.github.io/json/classnlohmann_1_1basic__json_a65753c68f06639eda0d355f919564e01.html#a65753c68f06639eda0d355f919564e01):

j["names"].get_to(names);

@nlohmann
Copy link
Owner

@chakpongchung Do you need further assistance?

@nlohmann nlohmann closed this as completed Jul 9, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind: bug 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