c++jsonnlohmann-json

Store std::optional value to json file c++


I have a std::optional<float> test;

I want to store this value to json file, and since it is optional, I donot know until runtime, if the variable has a value or not. So I am trying to do this

frameJson["Test"] = test.has_value() ? test.value() : std::nullopt;

But I get this error -

Error:Incompatible operand types ('const std::optional<float>::value_type' (aka 'const float') and 'const std::nullopt_t')

Question - How do I store the value of std::optional to json in all cases, meaning if its empty, then it has to be null or something meaningful.


Solution

  • How about

    frameJson["Test"] = test.has_value() ? basic_json(test.value()) : basic_json();