Skip to content

Maps with enum class keys which are convertible to JSON strings should be converted to JSON dictionaries #1217

Description

The following code:

#include <fstream>
#include <iomanip>
#include <iostream>
#include <unordered_map>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

enum class Species {
	DOG,
	OCTOPUS
};

void from_json(const json& j, Species& sp) {
	std::string s = j;
	if (s == "DOG") {
		sp = Species::DOG;
	} else if (s == "OCTOPUS") {
		sp = Species::OCTOPUS;
	} else {
		throw std::invalid_argument("Unknown species");
	}
}

void to_json(json& j, const Species sp) {
	if (sp == Species::DOG) {
		j = "DOG";
	} else {
		j = "OCTOPUS";
	}
}

int main() {
	json j;
	std::unordered_map<Species, bool> is_aquatic;
	is_aquatic[Species::DOG] = false;
	is_aquatic[Species::OCTOPUS] = true;
	j = is_aquatic;
	std::cout << j << std::endl;
}

produces the output [["DOG",false],["OCTOPUS",true]], which is not what the user would expect IMHO. Would it be possible to render this map as {"DOG":false,"OCTOPUS":true}?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions