json icon indicating copy to clipboard operation
json copied to clipboard

Add a convenience member function to call value_to

Open kiwixz opened this issue 1 year ago • 5 comments

Hi, first of all thanks for the great library fast yet easy to use.

I'm currently writing tag_invoke functions to convert JSON values from/to a class, and I have something like this:

MyClass{json.at("superint1").to_number<int>(),
        json.at("superint2").to_number<int>(),
        json.at("superbool").as_bool(),
        json.at("superstring").as_string(),
        boost::json::value_to<std::vector<int>>(json.at("supervectorofint"))}

It's a class with private values and a constructor, so I cant just rely on Boost Describe for this.

If there was a to<T>() member function (just calling boost::json::value_to under the hood), I could have arguably more consistent code:

MyClass{json.at("superint1").to_number<int>(),
        json.at("superint2").to_number<int>(),
        json.at("superbool").as_bool(),
        json.at("superstring").as_string(),
        json.at("supervectorofint").to<std::vector<int>>()}

And it could also allow something ever better (to my eyes that is!):

MyClass{json.at("superint1").to<int>(),
        json.at("superint2").to<int>(),
        json.at("superbool").to<bool>(),
        json.at("superstring").to<std::string>(),
        json.at("supervectorofint").to<std::vector<int>>()}

I like the fact that there is a fixed set of as_* functions, guaranteeing direct access to the underlying value; but value_to seems to be the "do whatever you need but get me this" convenience method I usually want.

Related to #418.

kiwixz avatar Feb 13 '24 17:02 kiwixz

You can still use Describe if you declare an intermediate struct holding the parameters.

pdimov avatar Feb 13 '24 18:02 pdimov

On second thought, isn't

MyClass{json.at("superint1").to<int>(),
        json.at("superint2").to<int>(),
        json.at("superbool").to<bool>(),
        json.at("superstring").to<std::string>(),
        json.at("supervectorofint").to<std::vector<int>>()}

possible to write today as

MyClass{
        value_to<int>(json.at("superint1")),
        value_to<int>(json.at("superint2")),
        value_to<bool>(json.at("superbool")),
        value_to<std::string>(json.at("superstring")),
        value_to<std::vector<int>>(json.at("supervectorofint"))
}

?

pdimov avatar Feb 17 '24 10:02 pdimov

It is. I think, @kiwixz considers that syntax too cumbersome.

To be honest, I'm not fond of adding just another way to call value_to.

grisumbras avatar Feb 17 '24 10:02 grisumbras

I didn't think of using namespace here which helps a lot.

It still feels weird to me to use it as a free function, especially when we have to_number as a member.

kiwixz avatar Feb 17 '24 23:02 kiwixz

True, but making an equivalent of value_to member function of value is much more intrusive.

grisumbras avatar Feb 19 '24 13:02 grisumbras