json
json copied to clipboard
Add into methods for Value
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()?
Seems reasonable. Would these return Option and just destroy your value if it is the wrong type?
Alternatively they could return Result and return the Value inside the Err variant.
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 amap_err(de::Error::custom)if you want to call it from a deserialize impl.<E> Result<_, E> where E: some trait—the way thatVisitormethods are structured. We could make this easily usable in a deserialize impl withoutmap_errbut 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.
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