Home > Back-end >  How to get number as std::string through nlohmann::json parsing?
How to get number as std::string through nlohmann::json parsing?

Time:04-09

#include <iostream>
#include <string>
#include <limits>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main()
{
    std::cout.precision(std::numeric_limits<double>::max_digits10);

    // create a JSON value with different types
    json json_types =
    {
        {"number_b", 1234567890.0123456789}
    };

    std::cout << std::fixed << json_types.dump(4) << std::endl;

    auto v2 = json_types["number_b"].get<double>();
    std::cout << "number_b in double: " << std::fixed << v2 << std::endl;

    // auto v3 = json_types["number_b"].get<std::string>();  
    // [json.exception.type_error.302] type must be string, but is number

}

Output:

{
    "number_b": 1234567890.0123458
}
number_b in double: 1234567890.01234579086303711

Is there a way that I can get the value of number_b as a std::string based on the original input value of "1234567890.0123456789"?

Note: the JSON number value is passed in through a third-party and I cannot change the input value from a number to a string from the source.

CodePudding user response:

A double has about 15-17 decimal places of precision [1]. A double cannot store 1234567890.0123456789 exactly and thus you will not be able to convert it to the exact string, if it is stored into a double first.

You can try to hook on the sax interface [2], that the nlohmann library provides (more specifically the number_float()) function to get the original string, that was present in the json during parsing.

I would however not rely on such hacks. Working with floating point numbers is inherently not exact and it is probably better to just look if the number is in a small range or something similar. This however depends on the exact problem that your are trying to solve.

CodePudding user response:

It's impossible.

  1. The example above lost precision on the compilation time.
  2. RFC7159. Technically you should not receive such JSON as an input source since software that sends you such JSON Number is usually conforming IEEE 754-2008.

A JSON number such as 1E400 or 3.141592653589793238462643383279 may indicate potential interoperability problems, since it suggests that the software that created it expects receiving software to have greater capabilities for numeric magnitude and precision than is widely available.

  • Related