Function json_with_comments::de::from_str
source · pub fn from_str<'de, D>(s: &'de str) -> Result<D>where
D: Deserialize<'de>,
Expand description
Deserialize a JSON with comments text as type D
.
§Examples
use serde::Deserialize;
#[derive(Deserialize)]
struct Country {
name: String,
code: u32,
regions: Vec<String>,
}
let jp = r#"
{
"name": "Japan",
"code": 81,
"regions": [
"Hokkaido",
"Kanto",
"Kyushu-Okinawa",
],
}"#;
let japan: Country = json_with_comments::from_str(jp).unwrap();
assert_eq!(japan.name, "Japan");
assert_eq!(japan.code, 81);
assert_eq!(japan.regions, ["Hokkaido", "Kanto", "Kyushu-Okinawa"]);
§Errors
This function can deserialize string as borrowed &str
.
But, if it contain escape sequence such as "\n"
, cannot deserialize and return Err
.
If you want to deserialize string value as escaped borrowed &str
, use from_str_raw
instead.
use std::borrow::Cow;
use json_with_comments::from_str;
let no_escaped = r#" "string without linefeed" "#;
assert_eq!(from_str::<String>(no_escaped).unwrap(), "string without linefeed");
assert_eq!(from_str::<Cow<'_, str>>(no_escaped).unwrap(), "string without linefeed");
assert_eq!(from_str::<&str>(no_escaped).unwrap(), "string without linefeed");
let escaped = r#" "string with linefeed\n" "#;
assert_eq!(from_str::<String>(escaped).unwrap(), "string with linefeed\n");
assert_eq!(from_str::<Cow<'_, str>>(escaped).unwrap(), "string with linefeed\n");
assert!(from_str::<&str>(escaped).is_err()); // cannot deserialize as &str because of its lifetime