json icon indicating copy to clipboard operation
json copied to clipboard

Add into methods for Value

Open retep998 opened this issue 7 years ago • 4 comments

Specifically into_object into_array and into_string. These methods would significantly improve ergonomics in certain cases by reducing large match expressions into simple method calls.

match json {
    Value::Object(x) => x,
    _ => return Err(Error::None),
}

vs

json.into_object()?

retep998 avatar Nov 27 '17 03:11 retep998

Seems reasonable. Would these return Option and just destroy your value if it is the wrong type?

dtolnay avatar Nov 30 '17 18:11 dtolnay

Alternatively they could return Result and return the Value inside the Err variant.

retep998 avatar Nov 30 '17 18:11 retep998

I think I would slightly prefer the Result way.

There are at least 3 reasonable error types:

  • Result<_, Value>—just give them back the value. I would prefer not to do this because it does not play well with ? and c-good-err.
  • Result<_, SomeConcreteError>—with an accessor for the original value. This could work but requires a map_err(de::Error::custom) if you want to call it from a deserialize impl.
  • <E> Result<_, E> where E: some trait—the way that Visitor methods are structured. We could make this easily usable in a deserialize impl without map_err but may require a type annotation elsewhere.

I would like to see an example of a deserialize impl using these into methods and see what we can do to make that ergonomic.

dtolnay avatar Nov 30 '17 18:11 dtolnay

I think I prefer the Option way, for several reasons

  • It seems intuitive and semantically correct
    • The absence of a specific data type does not necessarily indicate an "error"
  • It is consistent with the existing as_* methods, which all return Option
  • I've encountered the need for into_* methods on Value a few times before, and every time an Option-like implementation would have been more useful than a Result-like implementation
  • If the need arises to get back the value on type mismatch, the user can easily write a match statement
  • It avoids the bikeshedding about the Result::Err type from the previous comment

kangalio avatar Mar 20 '21 11:03 kangalio