Skip to content

Confused about iterating through json objects #49

@danpolanco

Description

@danpolanco

If I have:

{
  "england": {
    "name": "euro",
    "value": 57.99
  },
  "mexico": {
    "name": "peso",
    "value": 31.99
  },
  "us": {
    "name": "USD",
    "value": 42.99
  }
}

And I want to iterate through each, how would I do so?

My attempt so far has been similar to the following:

std::ifstream input_file( const string file_path );
nlohmann::json currencies_json;
currencies_json << input_file;
input_file.close();

unordered_map <string, currency_class> currencies;
for ( const auto currency_json: currencies_json ) {
    currency_class new_currency;

    new_currency[ "country" ] = ???
    new_currency[ "name" ] = ???
    new_currency[ "value"] = ???

    currencies[ country ] = new_currency;
}

I've tried it a a few ways including - for example - creating a string for new_currency[ "country" ] first and then storing it in it like new_currency[ "country" ] = my_string, but I get errors such as:

no member named 'key' in 'nlohmann::basic_json<std::map, std::vector, std::__1::basic_string<char>, bool, long long, double, std::allocator>'

or

[....]:1073:20: error: 'm_it' is a private member of 'nlohmann::basic_json<std::map, std::vector, std::__1::basic_string<char>,
      bool, long long, double, std::allocator>::const_iterator'
           result.m_it.object_iterator = m_value.object->find(key);
                   ^
[...]:89:32: note: in instantiation of member function 'nlohmann::basic_json<std::map, std::vector, std::__1::basic_string<char>, bool, long long, double,
      std::allocator>::find' requested here
                const auto iterator = currencies.find("country");
                                             ^
[...]/build/dependencies/json-prefix/src/json/src/json.hpp:3007:96: note: declared private here
        internal_iterator<typename array_t::const_iterator, typename object_t::const_iterator> m_it;

Could you provide some guidance? I'd really appreciate it!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions