Skip to content

[C++17] Allow std::optional to convert to nlohmann::json #1749

Description

@Treeston

This is what I assume to be a fairly minor change to the library's logic, but would represent a large improvement in usability.

Feature request

C++17 adds std::optional<T>. Let std::optional<T> convert to nlohmann::json.

If std::optional<T> is empty, I would expect this to result in null - if std::optional<T>, I would expect it to result in the contained value converted.

Use case example

The change would simplify (especially nested) uses of std::optional.

For example, imagine a simple key-value map, where each integer key can optionally have a localized string representation for each of 8 locales. The client dynamically selects the "best" available locale depending on user preferences.

In server code, one could express this as a std::vector<std::array<std::optional<std::string>, 8>>.
Currently, this type does not convert to nlohmann::json because std::optional<std::string> does not - resulting in needing to allocate a bunch of temporaries so the inner conversions can be done "manually".

Allowing std::optional to convert to nlohmann::json would simplify this logic greatly.

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions