I 'm getting a json response from a server of the following format :
{"value": 98.3}
However there are cases that the response can be :
{"value": null}
I have written a C++ program that uses boost json in order to parse this and get the value as float
#include <iostream>
#include <string>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
using namespace std;
namespace pt = boost::property_tree;
int main(int argc, char **argv)
{
try
{
float valuef;
pt::ptree root;
std::stringstream ss;
string result;
std::ifstream file("test.json");
if (file)
{
ss << file.rdbuf();
file.close();
}
pt::read_json(ss, root);
auto value = root.get<string>("value");
if (value != "null")
{
valuef = stof(value);
}
cout <<"float value is" << valuef << endl;
}
catch (std::exception &e)
{
string err = e.what();
cout << "error is " << endl
<< err << endl;
}
}
So I always check if the value is not equal with the literal "null" because according to this
Boost Json with null elements
outputting nulls is not supported.
Since the post is 7 years old I was wondering whether the latest boost libraries support something more generic to check for null values ?