json_pointer/lib.rs
1//! A crate for parsing and using JSON pointers, as specified in [RFC
2//! 6901](https://tools.ietf.org/html/rfc6901). Unlike the `pointer` method
3//! built into `serde_json`, this handles both validating JSON Pointers before
4//! use and the URI Fragment Identifier Representation.
5//!
6//! [](https://travis-ci.org/remexre/json-pointer)
7//! [](https://crates.io/crates/json-pointer)
8//! [](https://docs.rs/json-pointer)
9//!
10//! ## Creating a JSON Pointer
11//!
12//! JSON pointers can be created with a literal `[&str]`, or parsed from a `String`.
13//!
14//! ```rust
15//! extern crate json_pointer;
16//!
17//! use json_pointer::JsonPointer;
18//!
19//! fn main() {
20//! let from_strs = JsonPointer::new([
21//! "foo",
22//! "bar",
23//! ]);
24//! let parsed = "/foo/bar".parse::<JsonPointer<_, _>>().unwrap();
25//!
26//! assert_eq!(from_strs.to_string(), parsed.to_string());
27//! }
28//! ```
29//!
30//! ## Using a JSON Pointer
31//!
32//! The `JsonPointer` type provides `.get()` and `.get_mut()`, to get references
33//! and mutable references to the appropriate value, respectively.
34//!
35//! ```rust
36//! extern crate json_pointer;
37//! #[macro_use]
38//! extern crate serde_json;
39//!
40//! use json_pointer::JsonPointer;
41//!
42//! fn main() {
43//! let ptr = "/foo/bar".parse::<JsonPointer<_, _>>().unwrap();
44//!
45//! let document = json!({
46//! "foo": {
47//! "bar": 0,
48//! "baz": 1,
49//! },
50//! "quux": "xyzzy"
51//! });
52//!
53//! let indexed = ptr.get(&document).unwrap();
54//!
55//! assert_eq!(indexed, &json!(0));
56//! }
57//! ```
58//!
59//! ## URI Fragment Identifier Representation
60//!
61//! JSON Pointers can be embedded in the fragment portion of a URI. This is the
62//! reason why most JSON pointer libraries require a `#` character at the beginning
63//! of a JSON pointer. The crate will detect the leading `#` as an indicator to
64//! parse in URI Fragment Identifier Representation. Note that this means that this
65//! crate does not support parsing full URIs.
66//!
67//! ```rust
68//! extern crate json_pointer;
69//!
70//! use json_pointer::JsonPointer;
71//!
72//! fn main() {
73//! let str_ptr = "/f%o".parse::<JsonPointer<_, _>>().unwrap();
74//! let uri_ptr = "#/f%25o".parse::<JsonPointer<_, _>>().unwrap();
75//!
76//! assert_eq!(str_ptr, uri_ptr);
77//! }
78//! ```
79
80#![deny(missing_docs)]
81
82mod parser;
83mod ptr;
84
85pub use parser::ParseError;
86pub use ptr::IndexError;
87pub use ptr::JsonPointer;