Created
July 29, 2018 17:42
-
-
Save Isan-Rivkin/6c80ce7a6fc3155477707307429244b1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[macro_use] | |
extern crate serde_json; | |
extern crate json_patch; | |
use json_patch::{patch, diff, from_value}; | |
use serde_json::from_str; | |
use json_patch::merge; | |
fn create_and_patch_document_using_json_patch(){ | |
let mut doc = json!([ | |
{ "name": "Andrew" }, | |
{ "name": "Maxim" } | |
]); | |
let p = from_str(r#"[ | |
{ "op": "test", "path": "/0/name", "value": "Andrew" }, | |
{ "op": "add", "path": "/0/happy", "value": true } | |
]"#).unwrap(); | |
patch(&mut doc, &p).unwrap(); | |
assert_eq!(doc, json!([ | |
{ "name": "Andrew", "happy": true }, | |
{ "name": "Maxim" } | |
])); | |
} | |
fn create_and_patch_document_using_json_merge_patch(){ | |
let mut doc = json!({ | |
"title": "Goodbye!", | |
"author" : { | |
"givenName" : "John", | |
"familyName" : "Doe" | |
}, | |
"tags":[ "example", "sample" ], | |
"content": "This will be unchanged" | |
}); | |
let patch = json!({ | |
"title": "Hello!", // replace | |
"phoneNumber": "+01-123-456-7890", // add new | |
"author": { // remove familyName param completley | |
"familyName": null | |
}, | |
"tags": [ "example" ] //remove sample | |
}); | |
merge(&mut doc, &patch); | |
assert_eq!(doc, json!({ | |
"title": "Hello!", | |
"author" : { | |
"givenName" : "John" | |
}, | |
"tags": [ "example" ], | |
"content": "This will be unchanged", | |
"phoneNumber": "+01-123-456-7890" | |
})); | |
} | |
fn diff_2_jsons(){ | |
let left = json!({ | |
"title": "Goodbye!", | |
"author" : { | |
"givenName" : "John", | |
"familyName" : "Doe" | |
}, | |
"tags":[ "example", "sample" ], | |
"content": "This will be unchanged" | |
}); | |
let right = json!({ | |
"title": "Hello!", | |
"author" : { | |
"givenName" : "John" | |
}, | |
"tags": [ "example" ], | |
"content": "This will be unchanged", | |
"phoneNumber": "+01-123-456-7890" | |
}); | |
let p = diff(&left, &right); | |
assert_eq!(p, from_value(json!([ | |
{ "op": "remove", "path": "/author/familyName" }, | |
{ "op": "remove", "path": "/tags/1" }, | |
{ "op": "replace", "path": "/title", "value": "Hello!" }, | |
{ "op": "add", "path": "/phoneNumber", "value": "+01-123-456-7890" }, | |
])).unwrap()); | |
let mut doc = left.clone(); | |
patch(&mut doc, &p).unwrap(); | |
assert_eq!(doc, right); | |
} | |
fn main() { | |
create_and_patch_document_using_json_patch(); | |
create_and_patch_document_using_json_merge_patch(); | |
diff_2_jsons(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment