Mahesh Bansod
Mahesh Bansod

Reputation: 2033

convert an object to serde_json::Value without serializing and deserializing

I have this struct that has a field containing type Option<serde_json::Value>

I want to be able to store any object( i.e. object created by any struct) in that field. The current approach I'm using is to first convert the object to JSON string (using serde_json::to_string) and then convert it again to serde_json::Value using serde_json::from_str .

I'm doing this so that I can send different kinds of JSON requests with arbitrary data.

So, is there a way to convert any serde-serializable object to serde_json::Value without doing a serde_json::to_string and serde_json::from_str ? If I'm going the wrong way with this, please suggest a better one, ty!

Upvotes: 11

Views: 4830

Answers (1)

user2722968
user2722968

Reputation: 16475

There is serde_json::value::to_value() specifically for this:

pub fn to_value<T>(value: T) -> Result<Value, Error>  where
    T: Serialize,

That is, to_value takes any T that is Serialize and gives you a Value or an error (in case serialization fails).

Upvotes: 14

Related Questions