8

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!

Mahesh Bansod
  • 1,493
  • 2
  • 24
  • 42

1 Answers1

10

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).

user2722968
  • 13,636
  • 2
  • 46
  • 67