Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Should TryFrom be implemented for Value? #738

Closed
amandasaurus opened this issue Jan 1, 2021 · 3 comments
Closed

Should TryFrom be implemented for Value? #738

amandasaurus opened this issue Jan 1, 2021 · 3 comments

Comments

@amandasaurus
Copy link
Contributor

serde_json::Value has various as_* methods which allow conversion to the underlying enum (e.g. as_bool, as_str). Rust now has a TryFrom trait. Should TryFrom be implemented for Value for things like this? I'm willing to add this myself, but first, I'd like to check it would be accepted, or if there's a good reason it hasn't been implemented yet.

@dtolnay
Copy link
Member

dtolnay commented Jan 1, 2021

I think I would prefer not to add those. This use case is already covered by the Deserialize trait in a more flexible way that works for extracting a vector, struct etc as well.

let x = u64::deserialize(&value)?;

@dtolnay dtolnay closed this as completed Jan 1, 2021
@amandasaurus
Copy link
Contributor Author

Deserializing to a u64 (etc) isn't much of a problem, right? But what about Vec<_>s or Strings? (i.e. serde_json::Value::Array or serde_json::Value::String) Is there an easy way to “If this is an array, return a refence to a slice, if not return None (or Err(_))”?. And likewise for String and &str?

If you're using JSON know the data layout, then serde's Serialization/Deserialization makes a lot of sense to convert to proper Rust structs. But I think people will often have a blob of JSON they will need to work with “dynamically”. The std::convert traits are very useful here, no?

For a geojson bug report, I attempted to use the T::deserialize approach, (patch here). It works for u64/etc. But how can I (optionally) return a reference to a slice for arrays (etc.)?

@amandasaurus
Copy link
Contributor Author

Given that From<u64> for Value (etc.) is implemented, surely the reciprocal TryFrom<Value> for u64 (etc.) should be implemented too?

@serde-rs serde-rs locked and limited conversation to collaborators Jul 4, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Development

No branches or pull requests

2 participants