json_spanned_value/
lib.rs

1//! Track the origin of your json values for better error reporting!
2//! The [toml] crate has [toml-spanned-value] for this.
3//! [serde_json] now has [json-spanned-value].
4//! 
5//! The basic crates provide users with a `Value` type that can be used for custom parsing logic.
6//! However, this type doesn't support span information.
7//! In some cases it's possible to extract line/column information out of error messages,
8//! but that's awkward and error prone - often reporting errors on the next line
9//! (e.g. where the seek position of the underlying reader has skipped to.)
10//!
11//!
12//!
13//! [serde_json]:           https://docs.rs/serde_json/
14//! [toml]:                 https://docs.rs/toml/
15//! [toml-spanned-value]:   https://docs.rs/toml-spanned-value/
16//! [json-spanned-value]:   https://docs.rs/json-spanned-value/
17#![forbid(missing_docs)]
18#![forbid(unsafe_code)]
19
20mod error_ext;              pub use error_ext::*;
21mod map;                    pub use map::Map;
22mod reader;                 pub(crate) use reader::*;
23mod settings;               pub use settings::*;
24mod shared;                 pub(crate) use shared::*;
25pub mod spanned;            pub use spanned::Spanned;
26mod stream_deserializer;    pub use stream_deserializer::StreamDeserializer;
27mod value;                  pub use value::Value;
28
29#[cfg(test)] mod tests;
30
31
32
33use serde_json::error as sje;
34use serde::de;
35use std::sync::Arc;
36
37
38/// Read json from a slice of in-memory bytes, with explicit [Settings]
39pub fn from_slice_with_settings<T: de::DeserializeOwned>(buf: &[u8], settings: &Settings) -> sje::Result<T> {
40    let shared = Arc::new(Shared::new(settings));
41    let _shared_stack = SharedStack::push(shared.clone());
42    // NOTE:  Our use of from_reader forces us to use DeserializeOwned
43    serde_json::from_reader(Reader::new(buf, shared))
44}
45
46/// Read json from a slice of in-memory bytes, with default [Settings]
47pub fn from_slice<T: de::DeserializeOwned>(buf: &[u8]) -> sje::Result<T> {
48    from_slice_with_settings(buf, &Settings::default())
49}
50
51/// Read json from an in-memory string, with explicit [Settings]
52pub fn from_str_with_settings<T: de::DeserializeOwned>(buf: &str, settings: &Settings) -> sje::Result<T> {
53    from_slice_with_settings(buf.as_bytes(), settings)
54}
55
56/// Read json from an in-memory string, with default [Settings]
57pub fn from_str<T: de::DeserializeOwned>(buf: &str) -> sje::Result<T> {
58    from_slice(buf.as_bytes())
59}