Home > Mobile >  How to check a value for null when using boost json ptree
How to check a value for null when using boost json ptree

Time:10-07

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 ?

CodePudding user response:

Using the boost/property_tree/json_parser.hpp you can only check the string version like you said:

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.

However, since boost version 1.75.0, you can also use boost/json.hpp for working with JSON objects.

A parsed JSON object is now of type json::value and the types are specified with json::kind. See boost.org's example.

Thus, with the value you would be able to do something like:

// jv is a value from a kvp-pair
if(jv.is_null()) {
 // Json value is null
}

Refer to the boost's example for the implementation specifics.

CodePudding user response:

No. From the documentation:

JSON values are mapped to nodes containing the value. However, all type information is lost; numbers, as well as the literals "null", "true" and "false" are simply mapped to their string form.

  • Related