Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: remove_by_pointer method #912

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions src/value/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -828,6 +828,69 @@ impl Value {
})
}

/// Removes a value by a JSON Pointer and returns that value.
///
/// JSON Pointer defines a string syntax for identifying a specific value
/// within a JavaScript Object Notation (JSON) document.
///
/// A Pointer is a Unicode string with the reference tokens separated by `/`.
/// Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The
/// addressed value is returned and if there is no such value `None` is
/// returned.
///
/// For more information, read [RFC6901](https://tools.ietf.org/html/rfc6901).
///
/// # Example of Use
///
/// ```
/// # use serde_json::{Value, json};
/// #
/// let mut data = json!({
/// "x": {
/// "y": ["z", "zz"]
/// }
/// });
///
/// let v = data.remove_by_pointer("/x/y/0");
/// assert_eq!(v, Some(json!("z")));
/// assert_eq!(
/// data,
/// json!({
/// "x": {
/// "y": ["zz"]
/// }
/// }),
/// );
///
/// let v = data.remove_by_pointer("/x/y");
/// assert_eq!(v, Some(json!(["zz"])));
/// assert_eq!(data, json!({ "x": {} }));
///
/// let v = data.remove_by_pointer("");
/// assert_eq!(v, Some(json!({ "x": {} })));
/// assert_eq!(data, Value::Null);
/// ```
pub fn remove_by_pointer(&mut self, pointer: &str) -> Option<Value> {
if pointer.is_empty() {
return Some(self.take());
}
#[allow(clippy::manual_split_once)]
let mut pointer_split = pointer.rsplitn(2, '/');
let key = pointer_split.next()?;
let pointer = pointer_split.next()?;
self.pointer_mut(pointer).and_then(|value| match value {
Value::Object(map) => map.remove(key),
Value::Array(list) => parse_index(key).and_then(move |x| {
if x < list.len() {
Some(list.remove(x))
} else {
None
}
}),
_ => None,
})
}

/// Takes the value out of the `Value`, leaving a `Null` in its place.
///
/// ```
Expand Down