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)?

3
  • 1
    Possible duplicate of C++ string to double conversion Commented Aug 4, 2017 at 12:47
  • What happens when you try like this: Json::Value val = arr[0]; double x = val.asDouble(); Commented Aug 4, 2017 at 13:09
  • what is the return value of arr.isArray() ? Commented Aug 4, 2017 at 14:49

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
Json do support floating point numbers; see 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.
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
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.