1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
//! JSON configuration parser.
//!
//! This is only usable if you enabled `json` Cargo feature.
//!
//! ### Example
//! ```rust
//! use plugx_config::parser::{ConfigurationParser, json::ConfigurationParserJson};
//! use plugx_input::Input;
//!
//! let bytes = br#"
//! {
//! "hello": ["w", "o", "l", "d"],
//! "foo": {
//! "bar": {
//! "baz": "Qux",
//! "abc": 3.14
//! },
//! "xyz": false
//! }
//! }
//! "#;
//!
//! let parser = ConfigurationParserJson::new();
//! let parsed: Input = parser.parse(bytes.as_slice()).unwrap();
//!
//! assert!(parsed.is_map());
//! let map = parsed.as_map();
//! assert!(
//! map.len() == 2 &&
//! map.contains_key("foo") &&
//! map.contains_key("hello")
//! );
//! ```
use crate::parser::ConfigurationParser;
use anyhow::anyhow;
use cfg_if::cfg_if;
use plugx_input::Input;
use std::fmt::{Debug, Display, Formatter};
#[derive(Clone, Copy, Default)]
pub struct ConfigurationParserJson;
impl Display for ConfigurationParserJson {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str("JSON parser")
}
}
impl Debug for ConfigurationParserJson {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ConfigurationParserJson").finish()
}
}
impl ConfigurationParserJson {
pub fn new() -> Self {
Default::default()
}
}
impl ConfigurationParser for ConfigurationParserJson {
fn name(&self) -> String {
"JSON".into()
}
fn supported_format_list(&self) -> Vec<String> {
["json".into()].into()
}
fn try_parse(&self, bytes: &[u8]) -> anyhow::Result<Input> {
serde_json::from_slice(bytes)
.map(|parsed: Input| {
cfg_if! {
if #[cfg(feature = "tracing")] {
tracing::trace!(
input=String::from_utf8_lossy(bytes).to_string(),
output=%parsed,
"Parsed JSON contents"
);
} else if #[cfg(feature = "logging")] {
log::trace!(
"msg=\"Parsed JSON contents\" input={:?} output={:?}",
String::from_utf8_lossy(bytes).to_string(),
parsed.to_string()
);
}
}
parsed
})
.map_err(|error| anyhow!(error))
}
fn is_format_supported(&self, bytes: &[u8]) -> Option<bool> {
Some(serde_json::from_slice::<serde_json::Value>(bytes).is_ok())
}
}