#json-pointer #rfc-6901 #6901

jsonptr

Data structures and logic for resolving, assigning, and deleting by JSON Pointers (RFC 6901)

14 releases

Uses new Rust 2021

new 0.1.5 Jun 30, 2022
0.1.4 Jun 30, 2022
0.0.8 Jun 12, 2022

#241 in Data structures

Download history 24/week @ 2022-05-30 144/week @ 2022-06-06 82/week @ 2022-06-13 26/week @ 2022-06-20 65/week @ 2022-06-27

319 downloads per month

MIT/Apache

83KB
2K SLoC

jsonptr - JSON Pointers for Rust

github crates.io docs.rs build status

Data structures and logic for resolving, assigning, and deleting by JSON Pointers (RFC 6901).

Usage

Resolve

JSON Pointers can be created either with a slice of strings or directly from a properly encoded string representing a JSON Pointer.

use jsonptr::{Pointer, Resolve, ResolveMut};
use serde_json::json;

fn main() {
    let mut data = json!({
        "foo": {
            "bar": "baz"
        }
    });

    let ptr = Pointer::new(&["foo", "bar"]);
    ptr.resolve(&data);
    let bar = data.resolve(&ptr).unwrap();
    assert_eq!(bar, "baz");

    let ptr = Pointer::try_from("/foo/bar").unwrap();
    let mut bar = data.resolve_mut(&ptr).unwrap(); // alternatively: ptr.resolve_mut(&mut data);
    assert_eq!(bar, "baz");
}

Assign

use jsonptr::{Pointer, Assign};
use serde_json::json;

fn main() {
    let ptr = Pointer::try_from("/foo/bar").unwrap();
    let mut data = json!({});
    let val = json!("qux");
    let assignment = data.assign(&ptr, val);
    assert_eq!(data, json!({ "foo": { "bar": "qux" }}))
}

Delete

    use jsonptr::{Pointer, Delete};
    use serde_json::json;
fn main() {
    let mut data = json!({ "foo": { "bar": { "baz": "qux" } } });
    let ptr = Pointer::new(&["foo", "bar", "baz"]);
    assert_eq!(data.delete(&ptr), Ok(Some("qux".into())));
    assert_eq!(data, json!({ "foo": { "bar": {} } }));

    // unresolved pointers return Ok(None)
    let mut data = json!({});
    let ptr = Pointer::new(&["foo", "bar", "baz"]);
    assert_eq!(ptr.delete(&mut data), Ok(None));
    assert_eq!(data, json!({}));

    // replacing a root pointer replaces data with `Value::Null`
    let mut data = json!({ "foo": { "bar": "baz" } });
    let ptr = Pointer::default();
    assert_eq!(data.delete(&ptr), Ok(Some(json!({ "foo": { "bar": "baz" } }))));
    assert!(data.is_null());
}

Contributions / Issues

Contributions and feedback are always welcome and appreciated.

If you find an issue, please open a ticket or a pull request.

License

MIT or Apache 2.0.

Dependencies

~2.2–3MB
~95K SLoC