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

Why are elements alphabetized on key while iterating? #53

Closed
luxe opened this issue Apr 6, 2015 · 1 comment
Closed

Why are elements alphabetized on key while iterating? #53

luxe opened this issue Apr 6, 2015 · 1 comment

Comments

@luxe
Copy link
Contributor

luxe commented Apr 6, 2015

Let's say I have the json from the example readme:

  nlohmann::json all = {
  {"pi", 3.141},
  {"happy", true},
  {"name", "Niels"},
  {"nothing", nullptr},
  {"answer", {
    {"everything", 42}
  }},
  {"list", {1, 0, 2}},
  {"object", {
    {"currency", "USD"},
    {"value", 42.99}
  }}
};

I will iterate over it the following way:

  for (nlohmann::json::iterator it = all.begin(); it != all.end(); ++it) {
    std::cout << it.key() << std::endl;
  }

I would expect this:

pi
happy
name
nothing
answer
list
object

Instead, I get:

answer
happy
list
name
nothing
object
pi

Why is this the default? Can it be turned off?

@nlohmann
Copy link
Owner

nlohmann commented Apr 6, 2015

They are ordered by key, because they are internally stored in a container of type std::map<std::string, nlohmann::json> which by default uses std::less<std::string> as order. This default can be overridden by setting a different template parameter ObjectType. To be able to compile the code, this type has to conform to the AssociativeContainer concept.

I know there may be situations where it would be convenient to rely on a certain order of JSON object's elements, it would at the same time be non-compliant, because JSON defines objects as unordered list of values.

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

No branches or pull requests

2 participants