1

I am trying to take a string, that I know represents a decimal, from a JSON object and assign it to a double in C++.

One would expect that asDouble() does the job, but this is not the case. For example if we have the array ["0.4983", "4387"] sitting in a variable Json::Value arr, doing

double x = arr[0].asDouble()

throws an exception Value is not convertible to double.

What is the recommended way of doing this (in C++ 11)?

John S.
  • 501
  • 2
  • 6
  • 17

2 Answers2

2

My guess is that "0.4983" is a string, so jsoncpp refuses to convert it into a double. This is reasonable since normally to convert a string such as "abc" into a double makes no sense.

What you need is to manually convert the string to double; in C++11 it would be stod.

scinart
  • 457
  • 2
  • 9
  • This is actually what I'm doing at the moment. As far as I know - please correct me if I'm mistaken - Json does not support floating point numbers, only integers. So any decimal in Json would have to be represented by a string, i.e. enclosed by double quotation marks. Given how common it is to pass decimals in a Json objects, I feel jsoncpp should provide a function to convert strings to doubles that throws an exception if no conversion is possible. After all, this is exactly what one would do when first reading into a `std::string` and then trying to convert to double with `std::stod`. – John S. Aug 07 '17 at 20:19
  • Json do support floating point numbers; see http://json.org/, and I believe a modern library of json will support it. But ``["4.5"]`` is an array of string, while ``[4.5]`` is an array of floating point numbers. – scinart Aug 08 '17 at 11:08
  • So basically it's bad form to put floating point numbers packaged as strings in a Json. Can only hope that the data provider will change this at some point, and have to go with conversion via `std::stod` until then. Thx – John S. Aug 09 '17 at 16:51
0

Just have a look at the source: https://github.com/oftc/jsoncpp/blob/master/src/lib_json/json_value.cpp#L852

Obviously in jsoncpp only int, uint, real, null and boolean could be coerced to double. string is not in the list.

There are many answers here at stackoverflow exmplaining how to do string->double conversion yourself. One of them: C++ string to double conversion

Additionally there is Value::isConvertibleTo() which allows you to find at runtime if a value is convertible to a type: https://github.com/oftc/jsoncpp/blob/master/src/lib_json/json_value.cpp#L924

fukanchik
  • 2,811
  • 24
  • 29