diff --git a/src/lib.rs b/src/lib.rs index 7803111..306678d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1262,15 +1262,45 @@ pub fn delete_path<'a>(json: &'a str, path: &'a str) -> Result 0 { + match json.as_bytes()[i] { + b'{' | b'[' => { + // We hit the beginning of an object or array, nothing to do + break; + }, + b',' => { + // We hit the trailing comma of a previous element, return JSON without it + return Ok(format!("{}{}", &json[..i].trim(), &json[value_end..].trim())) + } + _ => { + // Do nothing + } + } + if json.as_bytes()[i] == b',' { + return Ok(format!("{}{}", &json[..i].trim(), &json[value_end..].trim())) + } + i -= 1; + } + } + + + eprint!("value_begin: '{}'\n", json.as_bytes()[value_begin] as char); + eprint!("value_end: '{}'\n", json.as_bytes()[value_end] as char); + // Trim both sides of where the "key":"value" was and concat it back together Ok(format!("{}{}",&json[..key_start].trim(), &json[value_end..].trim())) } diff --git a/src/test.rs b/src/test.rs index 3ae2fe6..cecbb7a 100644 --- a/src/test.rs +++ b/src/test.rs @@ -37,12 +37,28 @@ fn index() { #[test] fn test_delete_path() { - let json = r#"{"object":{"subobject": {"field":" value" }}}"#; - + // Only key in object + let json = r#"{"object":{"subobject": {"field":" value"}}}"#; let want = r#"{"object":{"subobject": {}}}"#; + let got = delete_path(json, "object.subobject.field").unwrap(); + assert_eq!(want, got); + // First key in object + let json = r#"{"object":{"subobject": {"field":" value", "some": "other"}}}"#; + let want = r#"{"object":{"subobject": {"some": "other"}}}"#; let got = delete_path(json, "object.subobject.field").unwrap(); + assert_eq!(want, got); + + // Key in middle of object + let json = r#"{"object":{"subobject": {"field": "value", "some": "other", "another": "val"}}}"#; + let want = r#"{"object":{"subobject": {"field": "value","another": "val"}}}"#; + let got = delete_path(json, "object.subobject.some").unwrap(); + assert_eq!(want, got); + // // Last key in object + let json = r#"{"object":{"subobject": {"field": "value", "some": "other", "another": "val"}}}"#; + let want = r#"{"object":{"subobject": {"field": "value", "some": "other"}}}"#; + let got = delete_path(json, "object.subobject.another").unwrap(); assert_eq!(want, got); }