Skip to content

Instantly share code, notes, and snippets.

@danpolanco
Created March 18, 2015 00:00
Show Gist options
  • Save danpolanco/58cc137d39dbf758d2ed to your computer and use it in GitHub Desktop.
Save danpolanco/58cc137d39dbf758d2ed to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
#include <map>
using namespace std;
#include <json.hpp>
using json = nlohmann::json;
int main() {
json j_currencies = {
{"england", {
{"name", "euro"},
{"value", 57.99}
}},
{"mexico", {
{"name", "peso"},
{"value", 31.99}
}},
{"us", {
{"name", "USD"},
{"value", 42.99}
}}
};
struct currency {
std::string country{};
std::string name{};
unsigned int value{};
};
map <string, currency> currencies;
for ( auto iter = j_currencies.begin(); iter != j_currencies.end(); ++iter ) {
cout << iter.key() << endl;
cout << iter.value() << endl;
cout << iter->get<string>() << endl;
}
}
➜ json_test g++ --std=c++11 main.cpp -o main.exe && ./main.exe <<<
main.cpp:33:16: error: no member named 'key' in 'nlohmann::basic_json<std::map, std::vector, std::__1::basic_string<char>, bool, long long, double, std::allocator>::iterator'
cout << iter.key() << endl;
~~~~ ^
main.cpp:34:16: error: no member named 'value' in 'nlohmann::basic_json<std::map, std::vector, std::__1::basic_string<char>, bool, long long, double, std::allocator>::iterator'
cout << iter.value() << endl;
~~~~ ^
2 errors generated.
@nlohmann
Copy link

The key() and value() functions are no longer supported, because they are nonstandard and broke the reverse iterators.

However, without lines 33 and 34 I get the following runtime error:

libc++abi.dylib: terminating with uncaught exception of type std::logic_error: cannot cast object to NSt3__112basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEE
Abort trap: 6

@nlohmann
Copy link

This should work:

for ( auto iter = j_currencies.begin(); iter != j_currencies.end(); ++iter ) {
    cout << *iter << endl;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment