Function serde_json::value::to_value

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

Convert a T into serde_json::Value which is an enum that can represent any valid JSON data.

Example

use serde::Serialize;
use serde_json::json;

use std::error::Error;

#[derive(Serialize)]
struct User {
    fingerprint: String,
    location: String,
}

fn compare_json_values() -> Result<(), Box<Error>> {
    let u = User {
        fingerprint: "0xF9BA143B95FF6D82".to_owned(),
        location: "Menlo Park, CA".to_owned(),
    };

    // The type of `expected` is `serde_json::Value`
    let expected = json!({
        "fingerprint": "0xF9BA143B95FF6D82",
        "location": "Menlo Park, CA",
    });

    let v = serde_json::to_value(u).unwrap();
    assert_eq!(v, expected);

    Ok(())
}

Errors

This conversion can fail if T’s implementation of Serialize decides to fail, or if T contains a map with non-string keys.

use std::collections::BTreeMap;

fn main() {
    // The keys in this map are vectors, not strings.
    let mut map = BTreeMap::new();
    map.insert(vec![32, 64], "x86");

    println!("{}", serde_json::to_value(map).unwrap_err());
}