Skip to content

Ignore nullptr values on constructing json object from a container #1422

Description

@vassilisw

I use void to_json(json& j, const Bar& b) function. In some cases I would like this function to just assign nullptr to j. For example...

void to_json(nlohmann::json& j, const Bar& b) {
    if (b.value == __FLT_MAX__) {
        j = nullptr;
        return;
    }
    j["name"] = b.name;
    j["value"] = b.value;
}
...

    std::vector<Bar> bars;
    bars.emplace_back("b1", 1.234);
    bars.emplace_back("b2", __FLT_MAX__);
    bars.emplace_back("b3", __FLT_MAX__);

    nlohmann::json j(bars);
    std::cout << j.dump(4) << std::endl;

Output...

[
    {
        "name": "b1",
        "value": 1.232
    },
    null,
    null
]

Is there a way for nullptr objects to just get ignored when the json object is created?
Such that the object to be...

[
    {
        "name": "b1",
        "value": 1.232
    }
]

I am aware of the parser_callback_t, anything similar for this?

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

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions