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

nlohmann::json orders Json objects alphabetically #2

Open
AdamSlay opened this issue Jun 27, 2024 · 0 comments
Open

nlohmann::json orders Json objects alphabetically #2

AdamSlay opened this issue Jun 27, 2024 · 0 comments

Comments

@AdamSlay
Copy link
Owner

When trying to create a function map for the EntityManager::addComponent<component>() functions, I was running into an issue where the component objects would be added alphabetically which would result in segfaults as the AI component would always be added first. The AI component depends on the Transform component already being attached to the entity, thus the segfaults.

I couldn't figure out why this was happening as the function map itself is not alphabetical, nor are the entity template json files. Eventually I started digging into the nlohmann::json library which I am using in this project and I discovered that the default behavior for ordering json objects in the library is to sort them alphabetically:

Object Order
The JSON standard defines objects as "an unordered collection of zero or more name/value pairs". As such, an implementation does not need to preserve any specific order of object keys.

Default behavior: sort keys
The default type nlohmann::json uses a std::map to store JSON objects, and thus stores object keys sorted alphabetically.

Example:

#include <iostream>
#include "json.hpp"

using json = nlohmann::json;

int main()
{
    json j;
    j["one"] = 1;
    j["two"] = 2;
    j["three"] = 3;

    std::cout << j.dump(2) << '\n';
}

Output:

{
  "one": 1,
  "three": 3,
  "two": 2
} 

Alternative behavior: preserve insertion order
If you do want to preserve the insertion order, you can try the type nlohmann::ordered_json.

Example:

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

using ordered_json = nlohmann::ordered_json;

int main()
{
    ordered_json j;
    j["one"] = 1;
    j["two"] = 2;
    j["three"] = 3;

    std::cout << j.dump(2) << '\n';
}

Output:

{
  "one": 1,
  "two": 2,
  "three": 3
}

So, the EventManager.cpp file uses the nlohmann::unordered_json type.

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

No branches or pull requests

1 participant