Skip to content

JSON Pointer (RFC 6901) implementation for Rust

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT
Notifications You must be signed in to change notification settings

chanced/jsonptr

Repository files navigation

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

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

Resolve values

Pointer::resolve

use jsonptr::Pointer;
use serde_json::json;

let mut data = json!({ "foo": { "bar": "baz" } });
let ptr = Pointer::from_static("/foo/bar");
let bar = ptr.resolve(&data).unwrap();
assert_eq!(bar, "baz");

Resolve::resolve

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

let mut data = json!({ "foo": { "bar": "baz" } });
let ptr = Pointer::from_static("/foo/bar");
let bar = data.resolve(&ptr).unwrap();
assert_eq!(bar, "baz");

ResolveMut::resolve_mut

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

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

Assign

Pointer::assign

use jsonptr::Pointer;
use serde_json::json;

let ptr = Pointer::from_static("/foo/bar");
let mut data = json!({});
let _previous = ptr.assign(&mut data, "qux").unwrap();
assert_eq!(data, json!({"foo": { "bar": "qux" }}))

Assign::asign

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

let ptr = Pointer::from_static("/foo/bar");
let mut data = json!({});
let _previous = data.assign(&ptr, "qux").unwrap();
assert_eq!(data, json!({ "foo": { "bar": "qux" }}))

Delete

Pointer::delete

use jsonptr::Pointer;
use serde_json::json;

let mut data = json!({ "foo": { "bar": { "baz": "qux" } } });
let ptr = Pointer::from_static("/foo/bar/baz");
assert_eq!(ptr.delete(&mut data), Some("qux".into()));
assert_eq!(data, json!({ "foo": { "bar": {} } }));

// unresolved pointers return None
let mut data = json!({});
assert_eq!(ptr.delete(&mut data), None);

Delete::delete

use jsonptr::{ Pointer, delete::Delete };
use serde_json::json;

let mut data = json!({ "foo": { "bar": { "baz": "qux" } } });
let ptr = Pointer::from_static("/foo/bar/baz");
assert_eq!(ptr.delete(&mut data), Some("qux".into()));
assert_eq!(data, json!({ "foo": { "bar": {} } }));

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

Feature Flags

Flag Enables
"std" implements std::error::Error for errors

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.