├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── project.clj ├── src └── clj_json_patch │ ├── core.cljc │ └── util.cljc └── test └── clj_json_patch ├── core_test.clj ├── rfc6901_test.clj └── util_test.clj /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /classes 3 | /checkouts 4 | pom.xml 5 | pom.xml.asc 6 | *.jar 7 | *.class 8 | /.lein-* 9 | /.nrepl-port 10 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: clojure 2 | lein: lein 3 | script: lein midje 4 | sudo: required 5 | jdk: 6 | - oraclejdk9 7 | - openjdk11 8 | - openjdk10 9 | - openjdk9 10 | - openjdk8 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC 2 | LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM 3 | CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 4 | 5 | 1. DEFINITIONS 6 | 7 | "Contribution" means: 8 | 9 | a) in the case of the initial Contributor, the initial code and 10 | documentation distributed under this Agreement, and 11 | 12 | b) in the case of each subsequent Contributor: 13 | 14 | i) changes to the Program, and 15 | 16 | ii) additions to the Program; 17 | 18 | where such changes and/or additions to the Program originate from and are 19 | distributed by that particular Contributor. A Contribution 'originates' from 20 | a Contributor if it was added to the Program by such Contributor itself or 21 | anyone acting on such Contributor's behalf. Contributions do not include 22 | additions to the Program which: (i) are separate modules of software 23 | distributed in conjunction with the Program under their own license 24 | agreement, and (ii) are not derivative works of the Program. 25 | 26 | "Contributor" means any person or entity that distributes the Program. 27 | 28 | "Licensed Patents" mean patent claims licensable by a Contributor which are 29 | necessarily infringed by the use or sale of its Contribution alone or when 30 | combined with the Program. 31 | 32 | "Program" means the Contributions distributed in accordance with this 33 | Agreement. 34 | 35 | "Recipient" means anyone who receives the Program under this Agreement, 36 | including all Contributors. 37 | 38 | 2. GRANT OF RIGHTS 39 | 40 | a) Subject to the terms of this Agreement, each Contributor hereby grants 41 | Recipient a non-exclusive, worldwide, royalty-free copyright license to 42 | reproduce, prepare derivative works of, publicly display, publicly perform, 43 | distribute and sublicense the Contribution of such Contributor, if any, and 44 | such derivative works, in source code and object code form. 45 | 46 | b) Subject to the terms of this Agreement, each Contributor hereby grants 47 | Recipient a non-exclusive, worldwide, royalty-free patent license under 48 | Licensed Patents to make, use, sell, offer to sell, import and otherwise 49 | transfer the Contribution of such Contributor, if any, in source code and 50 | object code form. This patent license shall apply to the combination of the 51 | Contribution and the Program if, at the time the Contribution is added by the 52 | Contributor, such addition of the Contribution causes such combination to be 53 | covered by the Licensed Patents. The patent license shall not apply to any 54 | other combinations which include the Contribution. No hardware per se is 55 | licensed hereunder. 56 | 57 | c) Recipient understands that although each Contributor grants the licenses 58 | to its Contributions set forth herein, no assurances are provided by any 59 | Contributor that the Program does not infringe the patent or other 60 | intellectual property rights of any other entity. Each Contributor disclaims 61 | any liability to Recipient for claims brought by any other entity based on 62 | infringement of intellectual property rights or otherwise. As a condition to 63 | exercising the rights and licenses granted hereunder, each Recipient hereby 64 | assumes sole responsibility to secure any other intellectual property rights 65 | needed, if any. For example, if a third party patent license is required to 66 | allow Recipient to distribute the Program, it is Recipient's responsibility 67 | to acquire that license before distributing the Program. 68 | 69 | d) Each Contributor represents that to its knowledge it has sufficient 70 | copyright rights in its Contribution, if any, to grant the copyright license 71 | set forth in this Agreement. 72 | 73 | 3. REQUIREMENTS 74 | 75 | A Contributor may choose to distribute the Program in object code form under 76 | its own license agreement, provided that: 77 | 78 | a) it complies with the terms and conditions of this Agreement; and 79 | 80 | b) its license agreement: 81 | 82 | i) effectively disclaims on behalf of all Contributors all warranties and 83 | conditions, express and implied, including warranties or conditions of title 84 | and non-infringement, and implied warranties or conditions of merchantability 85 | and fitness for a particular purpose; 86 | 87 | ii) effectively excludes on behalf of all Contributors all liability for 88 | damages, including direct, indirect, special, incidental and consequential 89 | damages, such as lost profits; 90 | 91 | iii) states that any provisions which differ from this Agreement are offered 92 | by that Contributor alone and not by any other party; and 93 | 94 | iv) states that source code for the Program is available from such 95 | Contributor, and informs licensees how to obtain it in a reasonable manner on 96 | or through a medium customarily used for software exchange. 97 | 98 | When the Program is made available in source code form: 99 | 100 | a) it must be made available under this Agreement; and 101 | 102 | b) a copy of this Agreement must be included with each copy of the Program. 103 | 104 | Contributors may not remove or alter any copyright notices contained within 105 | the Program. 106 | 107 | Each Contributor must identify itself as the originator of its Contribution, 108 | if any, in a manner that reasonably allows subsequent Recipients to identify 109 | the originator of the Contribution. 110 | 111 | 4. COMMERCIAL DISTRIBUTION 112 | 113 | Commercial distributors of software may accept certain responsibilities with 114 | respect to end users, business partners and the like. While this license is 115 | intended to facilitate the commercial use of the Program, the Contributor who 116 | includes the Program in a commercial product offering should do so in a 117 | manner which does not create potential liability for other Contributors. 118 | Therefore, if a Contributor includes the Program in a commercial product 119 | offering, such Contributor ("Commercial Contributor") hereby agrees to defend 120 | and indemnify every other Contributor ("Indemnified Contributor") against any 121 | losses, damages and costs (collectively "Losses") arising from claims, 122 | lawsuits and other legal actions brought by a third party against the 123 | Indemnified Contributor to the extent caused by the acts or omissions of such 124 | Commercial Contributor in connection with its distribution of the Program in 125 | a commercial product offering. The obligations in this section do not apply 126 | to any claims or Losses relating to any actual or alleged intellectual 127 | property infringement. In order to qualify, an Indemnified Contributor must: 128 | a) promptly notify the Commercial Contributor in writing of such claim, and 129 | b) allow the Commercial Contributor tocontrol, and cooperate with the 130 | Commercial Contributor in, the defense and any related settlement 131 | negotiations. The Indemnified Contributor may participate in any such claim 132 | at its own expense. 133 | 134 | For example, a Contributor might include the Program in a commercial product 135 | offering, Product X. That Contributor is then a Commercial Contributor. If 136 | that Commercial Contributor then makes performance claims, or offers 137 | warranties related to Product X, those performance claims and warranties are 138 | such Commercial Contributor's responsibility alone. Under this section, the 139 | Commercial Contributor would have to defend claims against the other 140 | Contributors related to those performance claims and warranties, and if a 141 | court requires any other Contributor to pay any damages as a result, the 142 | Commercial Contributor must pay those damages. 143 | 144 | 5. NO WARRANTY 145 | 146 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON 147 | AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER 148 | EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR 149 | CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A 150 | PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the 151 | appropriateness of using and distributing the Program and assumes all risks 152 | associated with its exercise of rights under this Agreement , including but 153 | not limited to the risks and costs of program errors, compliance with 154 | applicable laws, damage to or loss of data, programs or equipment, and 155 | unavailability or interruption of operations. 156 | 157 | 6. DISCLAIMER OF LIABILITY 158 | 159 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY 160 | CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, 161 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION 162 | LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 163 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 164 | ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE 165 | EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY 166 | OF SUCH DAMAGES. 167 | 168 | 7. GENERAL 169 | 170 | If any provision of this Agreement is invalid or unenforceable under 171 | applicable law, it shall not affect the validity or enforceability of the 172 | remainder of the terms of this Agreement, and without further action by the 173 | parties hereto, such provision shall be reformed to the minimum extent 174 | necessary to make such provision valid and enforceable. 175 | 176 | If Recipient institutes patent litigation against any entity (including a 177 | cross-claim or counterclaim in a lawsuit) alleging that the Program itself 178 | (excluding combinations of the Program with other software or hardware) 179 | infringes such Recipient's patent(s), then such Recipient's rights granted 180 | under Section 2(b) shall terminate as of the date such litigation is filed. 181 | 182 | All Recipient's rights under this Agreement shall terminate if it fails to 183 | comply with any of the material terms or conditions of this Agreement and 184 | does not cure such failure in a reasonable period of time after becoming 185 | aware of such noncompliance. If all Recipient's rights under this Agreement 186 | terminate, Recipient agrees to cease use and distribution of the Program as 187 | soon as reasonably practicable. However, Recipient's obligations under this 188 | Agreement and any licenses granted by Recipient relating to the Program shall 189 | continue and survive. 190 | 191 | Everyone is permitted to copy and distribute copies of this Agreement, but in 192 | order to avoid inconsistency the Agreement is copyrighted and may only be 193 | modified in the following manner. The Agreement Steward reserves the right to 194 | publish new versions (including revisions) of this Agreement from time to 195 | time. No one other than the Agreement Steward has the right to modify this 196 | Agreement. The Eclipse Foundation is the initial Agreement Steward. The 197 | Eclipse Foundation may assign the responsibility to serve as the Agreement 198 | Steward to a suitable separate entity. Each new version of the Agreement will 199 | be given a distinguishing version number. The Program (including 200 | Contributions) may always be distributed subject to the version of the 201 | Agreement under which it was received. In addition, after a new version of 202 | the Agreement is published, Contributor may elect to distribute the Program 203 | (including its Contributions) under the new version. Except as expressly 204 | stated in Sections 2(a) and 2(b) above, Recipient receives no rights or 205 | licenses to the intellectual property of any Contributor under this 206 | Agreement, whether expressly, by implication, estoppel or otherwise. All 207 | rights in the Program not expressly granted under this Agreement are 208 | reserved. 209 | 210 | This Agreement is governed by the laws of the State of Washington and the 211 | intellectual property laws of the United States of America. No party to this 212 | Agreement will bring a legal action under this Agreement more than one year 213 | after the cause of action arose. Each party waives its rights to a jury trial 214 | in any resulting litigation. 215 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | clj-json-patch 2 | ============== 3 | 4 | Clojure implementation of JSON Patch as specified in 5 | http://tools.ietf.org/html/rfc6902 with support for 6 | JSON Pointer https://tools.ietf.org/html/rfc6901 7 | 8 | [![Build Status](https://travis-ci.org/daviddpark/clj-json-patch.png)](https://travis-ci.org/daviddpark/clj-json-patch) 9 | 10 | 11 | Usage 12 | ----- 13 | ```clojure 14 | [clj-json-patch 0.1.7] 15 | 16 | ;; From some example namespace: 17 | (ns example.namespace 18 | (:require [clj-json-patch.core :refer :all])) 19 | ``` 20 | 21 | Generating patches with the diff function 22 | ----------------------------------------- 23 | 24 | ```clojure 25 | clj-json-patch.core=> (diff {"foo" "bar"} {"foo" ["bar"]}) 26 | [{"op" "replace", "path" "/foo", "value" ["bar"]}] 27 | 28 | clj-json-patch.core=> (diff {"foo" ["all" "grass" "cows" "eat"]} 29 | {"foo" ["all" "cows" "eat" "grass"]}) 30 | [{"op" "move", "from" "/foo/1", "path" "/foo/3"}] 31 | ``` 32 | 33 | Applying patches with the patch function 34 | ----------------------------------------- 35 | 36 | ```clojure 37 | clj-json-patch.core=> (patch {"foo" "bar"} [{"op" "replace", "path" "/foo", "value" ["bar"]}]) 38 | {"foo" ["bar"]} 39 | 40 | clj-json-patch.core=> (patch {"foo" ["all" "grass" "cows" "eat"]} 41 | [{"op" "move", "from" "/foo/1", "path" "/foo/3"}]) 42 | {"foo" ["all" "cows" "eat" "grass"]} 43 | ``` 44 | 45 | Run Unit Tests 46 | -------------- 47 | 48 | ```shell 49 | lein midje 50 | ``` 51 | -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject clj-json-patch "0.1.7" 2 | :description "Clojure implementation of http://tools.ietf.org/html/rfc6902" 3 | :url "http://github.com/daviddpark/clj-json-patch" 4 | :license {:name "Eclipse Public License" 5 | :url "http://www.eclipse.org/legal/epl-v10.html"} 6 | :main clj-json-patch.core 7 | :dependencies [[org.clojure/clojure "1.10.0"] 8 | [cheshire "5.8.0"]] 9 | :deploy-repositories [["releases" :clojars] 10 | ["snapshots" :clojars]] 11 | :profiles {:dev {:dependencies [[midje/midje "1.9.5"]] 12 | :plugins [[lein-midje "3.2.1"]]}}) 13 | -------------------------------------------------------------------------------- /src/clj_json_patch/core.cljc: -------------------------------------------------------------------------------- 1 | (ns clj-json-patch.core 2 | (:use [clj-json-patch.util :only [apply-patch diff* *keywordize*]])) 3 | 4 | 5 | (defn call-apply-patch 6 | [obj patches] 7 | #?(:clj (reduce #(apply-patch %1 %2) obj patches) 8 | :cljs (reduce #(apply-patch %1 %2) (js->clj (.parse js/JSON obj)) 9 | (js->clj (.parse js/JSON patches))))) 10 | 11 | 12 | (defn patch 13 | "Applies a JSON patch document (multiple patches) to JSON object." 14 | ([obj patches] 15 | (call-apply-patch obj patches)) 16 | ([obj patches keywordize?] 17 | (binding [*keywordize* keywordize?] 18 | (call-apply-patch obj patches)))) 19 | 20 | (defn call-diff* 21 | [obj1 obj2 prefix] 22 | #?(:clj (diff* obj1 23 | obj2 24 | "/") 25 | :cljs (diff* (js->clj (.parse js/JSON obj1)) 26 | (js->clj (.parse js/JSON obj2)) 27 | "/"))) 28 | 29 | (defn diff 30 | "Prepares a JSON patch document representing the difference 31 | between two JSON objects." 32 | ([obj1 obj2] 33 | (call-diff* obj1 obj2 "/")) 34 | ([obj1 obj2 keywordize?] 35 | (binding [*keywordize* keywordize?] 36 | (call-diff* obj1 obj2 "/")))) 37 | -------------------------------------------------------------------------------- /src/clj_json_patch/util.cljc: -------------------------------------------------------------------------------- 1 | (ns clj-json-patch.util 2 | (:require #?(:clj [cheshire.core :as json]) 3 | [clojure.string :as clo-str])) 4 | 5 | 6 | (declare remove-patch-value) 7 | (declare transform-moves) 8 | (declare diff-vecs) 9 | (declare gen-op) 10 | 11 | (def ^:dynamic *keywordize* false) 12 | 13 | (defn diff* 14 | "Prepares a JSON patch document representing the difference 15 | between two JSON objects." 16 | [obj1 obj2 prefix] 17 | (transform-moves obj1 obj2 18 | (cond (and (vector? obj1) (vector? obj2)) 19 | (diff-vecs obj1 obj2 prefix) 20 | (and (map? obj1) (map? obj2)) 21 | (vec 22 | (flatten 23 | (remove nil? 24 | (concat 25 | (for [[k v1] obj1] 26 | (let [k* (name k) 27 | v2 (get obj2 k)] 28 | (cond (and (vector? v1) (vector? v2)) 29 | (diff* v1 v2 (str prefix k* "/")) 30 | (not (contains? obj2 k)) 31 | (gen-op ["remove" (str prefix k*)]) 32 | (and (map? v1) (map? v2)) 33 | (diff* v1 v2 (str prefix k* "/")) 34 | (and (contains? obj2 k) 35 | (not= v1 v2)) 36 | (gen-op ["replace" (str prefix k*) v2])))) 37 | (for [[k v2] obj2] 38 | (let [k* (name k) 39 | v1 (get obj1 k)] 40 | (cond (not (contains? obj1 k)) 41 | (gen-op ["add" (str prefix k*) v2]))))))))))) 42 | (defn eval-escape-characters 43 | [segment] 44 | (clo-str/replace segment #"(~0|~1)" 45 | (fn [[_ s]] (cond (= s "~0") "~" 46 | (= s "~1") "/")))) 47 | 48 | (defn inject-escape-characters 49 | [segment] 50 | (clo-str/replace segment #"(~|\/)" 51 | (fn [[_ s]] (cond (= s "~") "~0" 52 | (= s "/") "~1")))) 53 | 54 | (defn ->key [seg] 55 | (if *keywordize* 56 | (keyword seg) 57 | seg)) 58 | 59 | (defn has-path? 60 | "given the patch path, determines if the path exists in the obj" 61 | [obj path] 62 | (let [path (if (.startsWith path "#") (subs path 1) path)] 63 | (cond 64 | (and obj (or (= path "") (= path "#"))) 65 | true 66 | (and (= path "/") (map? obj) (contains? obj "")) 67 | true 68 | :else 69 | (if-let [match (re-find #"^/([^/]+)(.*)" path)] 70 | (let [seg (eval-escape-characters (second match)) 71 | segs (nth match 2) 72 | [h-path? val] (let [ky (if (vector? obj) 73 | (Integer/parseInt seg) 74 | (->key seg))] 75 | [(contains? obj ky) 76 | (get obj ky)])] 77 | ;;(println :HAS "seg:" seg "segs:" segs "val:" val "h-path?" h-path?) 78 | (if (and h-path? (not (empty? segs))) 79 | (has-path? val segs) 80 | h-path?)))))) 81 | 82 | (defn get-patch-value 83 | "Given the patch path, find the associated value." 84 | [obj path] 85 | (let [path (if (clo-str/starts-with? path "#") (subs path 1) path)] 86 | (cond 87 | (or (= path "") (= path "#")) 88 | obj 89 | (and (= path "/") (map? obj) (get obj "")) 90 | (get obj "") 91 | :else 92 | (if-let [match (re-find #"^/([^/]+)(.*)" path)] 93 | (let [seg (eval-escape-characters (second match)) 94 | segs (nth match 2) 95 | val (cond (map? obj) 96 | (get obj (->key seg)) 97 | (vector? obj) 98 | (nth obj #?(:clj (Integer/parseInt seg) 99 | :cljs (js/parseInt seg))))] 100 | ;(println "seg:" seg "segs:" segs "val:" val) 101 | (if-not (empty? segs) 102 | (get-patch-value val segs) 103 | val)))))) 104 | 105 | (defn set-patch-value 106 | "Set val at path in obj" 107 | [obj path val & [insert]] 108 | (if-let [segs (re-seq #"/([^/]+)" path)] 109 | (if (> (count segs) 1) 110 | (if-let [path-exists (try (get-patch-value obj path) 111 | #?(:clj (catch Exception e 112 | (throw (Exception. (str "Unable to set value at '" path "'.")))) 113 | :cljs (catch js/Object e 114 | (throw (js/Error. (str "Unable to set value at '" path "'."))))))] 115 | (let [parent-path (apply str (map first (take (dec (count segs)) segs))) 116 | parent (get-patch-value obj parent-path)] 117 | (set-patch-value obj parent-path 118 | (set-patch-value parent (first (last segs)) val))) 119 | #?(:clj (throw (Exception. (str "Unable to set value at '" path 120 | "'. Consider adding a more explicit data " 121 | "structure as a child of an existing object."))) 122 | :cljs (throw (js/Error. (str "Unable to set value at '" path 123 | "'. Consider adding a more explicit data " 124 | "structure as a child of an existing object."))))) 125 | (cond (map? obj) 126 | (assoc obj (->key (eval-escape-characters (second (first segs)))) 127 | val) 128 | (vector? obj) 129 | (let [idx #?(:clj (Integer/parseInt (second (re-find #"/(\d+)" path))) 130 | :cljs (js/parseInt (second (re-find #"/(\d+)" path))))] 131 | (try 132 | (vec (concat (subvec obj 0 idx) 133 | [val] 134 | (subvec obj (if insert idx (inc idx))))) 135 | #?(:clj (catch Exception e 136 | (throw (Exception. (str "Unable to set value at " idx ".")))) 137 | :cljs (catch js/Object e 138 | (throw (js/Error. (str "Unable to set value at " idx "."))))))))) 139 | #?(:clj (throw (Exception. "Patch path must start with '/'")) 140 | :cljs (throw (js/Error. "Patch path must start with '/'"))))) ;Should be throwing an exception 141 | 142 | (defn add-patch-value 143 | "Add val at path in obj" 144 | [obj path val] 145 | (if-let [segs (re-seq #"/([^/]+)" path)] 146 | (if (> (count segs) 1) 147 | (let [parent-path (apply str (map first (take (dec (count segs)) segs))) 148 | parent (get-patch-value obj parent-path)] 149 | (if (vector? parent) 150 | (let [str-idx (last (last segs))] 151 | (if (or (= "-" str-idx) 152 | (= (count parent) #?(:clj (try (Integer/parseInt str-idx) 153 | (catch java.lang.NumberFormatException e 154 | (throw (Exception. (str "Unable to determine array index from '" str-idx "'."))))) 155 | :cljs (if (js/isNaN (js/parseInt str-idx)) 156 | (throw (js/Error. (str "Unable to determine array index from '" str-idx "'."))) 157 | (js/parseInt str-idx))))) 158 | (set-patch-value obj parent-path 159 | (conj parent val)) 160 | (let [first-last-seg (first (last segs)) 161 | insert (.endsWith path str-idx)] 162 | (set-patch-value obj parent-path 163 | (set-patch-value parent (first (last segs)) val insert))))) 164 | (if-let [path-exists (try (get-patch-value obj parent-path) 165 | #?(:clj (catch Exception e 166 | (throw (Exception. (str "Unable to set value at '" path "'.")))) 167 | :cljs (catch js/Object e 168 | (throw (js/Error. (str "Unable to set value at '" path "'."))))))] 169 | (set-patch-value obj parent-path 170 | (set-patch-value parent (first (last segs)) val)) 171 | #?(:clj (throw (Exception. (str "Unable to set value at '" path 172 | "'. Consider adding a more explicit data " 173 | "structure as a child of an existing object."))) 174 | :cljs (throw (js/Error. (str "Unable to set value at '" path 175 | "'. Consider adding a more explicit data " 176 | "structure as a child of an existing object."))))))) 177 | (set-patch-value obj path val)) 178 | #?(:clj (throw (Exception. "Patch path must start with '/'")) 179 | :cljs (throw (js/Error. "Patch path must start with '/'"))))) 180 | 181 | (defn move-patch-value 182 | "Move value located at 'from' to the 'path'." 183 | [obj from path] 184 | (if-let [to-segs (re-seq #"/([^/]+)" path)] 185 | (if-let [from-segs (re-seq #"/([^/]+)" from)] 186 | (let [val (get-patch-value obj from)] 187 | (if (some? val) 188 | (if (> (count to-segs) 1) 189 | (let [from-parent-path (apply str (map first (take (dec (count from-segs)) from-segs))) 190 | to-parent-path (apply str (map first (take (dec (count to-segs)) to-segs))) 191 | parent (get-patch-value obj to-parent-path)] 192 | (if (= from-parent-path to-parent-path) 193 | (set-patch-value obj from-parent-path 194 | (move-patch-value (get-patch-value obj from-parent-path) 195 | (first (last from-segs)) 196 | (first (last to-segs)))) 197 | (set-patch-value (remove-patch-value obj from) 198 | to-parent-path 199 | (set-patch-value parent (first (last to-segs)) val)))) 200 | (cond (map? obj) 201 | (-> obj 202 | (assoc (->key (second (first to-segs))) val) 203 | (dissoc (->key (second (first from-segs))))) 204 | (vector? obj) 205 | (let [from-int #?(:clj (try (Integer/parseInt (second (re-find #"/(\d+)" from))) 206 | (catch Exception e 207 | (throw (Exception. (str "Move attempted on value that does not exist at '" from "'."))))) 208 | :cljs (try (js/parseInt (second (re-find #"/(\d+)" from))) 209 | (catch js/Object e 210 | (throw (js/Error. (str "Move attempted on value that does not exist at '" from "'.")))))) 211 | to-int #?(:clj (try (Integer/parseInt (second (re-find #"/(\d+)" path))) 212 | (catch Exception e 213 | (throw (Exception. (str "Move attempted on value that does not exist at '" path "'."))))) 214 | :cljs (try (js/parseInt (second (re-find #"/(\d+)" path))) 215 | (catch js/Object e 216 | (throw (js/Error. (str "Move attempted on value that does not exist at '" path "'."))))))] 217 | (vec (concat (subvec obj 0 from-int) (subvec obj (inc from-int) (inc to-int)) 218 | [(get obj from-int)] (subvec obj (inc to-int))))))) 219 | #?(:clj (throw (Exception. (str "Move attempted on value that does not exist at '" from "'."))) 220 | :cljs (throw (js/Error. (str "Move attempted on value that does not exist at '" from "'.")))))) 221 | #?(:clj (throw (Exception. "Patch 'from' value must start with '/'")) 222 | :cljs (throw (js/Error. "Patch 'from' value must start with '/'")))) 223 | #?(:clj (throw (Exception. "Patch 'path' value must start with '/'")) 224 | :cljs (throw (js/Error. "Patch 'path' value must start with '/'"))))) 225 | 226 | (defn replace-patch-value 227 | "Replace the value found at 'path' with that bound to 'val'." 228 | [obj path val] 229 | ;;(println "path" obj path val (has-path? obj path)) 230 | (if (has-path? obj path) 231 | (if-let [segs (re-seq #"/([^/]+)" path)] 232 | (if (> (count segs) 1) 233 | (let [parent-path (apply str (map first (take (dec (count segs)) segs))) 234 | parent (get-patch-value obj parent-path)] 235 | (replace-patch-value obj parent-path 236 | (replace-patch-value parent (first (last segs)) val))) 237 | (cond (map? obj) 238 | (assoc obj (->key (second (first segs))) val) 239 | (vector? obj) 240 | (let [idx (Integer/parseInt (second (re-find #"/(\d+)" path)))] 241 | (vec (concat (subvec obj 0 idx) 242 | [val] 243 | (subvec obj (inc idx))))))) 244 | (throw (Exception. "Patch path must start with '/'"))) 245 | (throw (Exception. (str "Can't replace a value that does not exist at '" path "'."))))) 246 | 247 | (defn remove-patch-value 248 | "Remove the value at 'path' from obj." 249 | [obj path] 250 | (try 251 | (if (has-path? obj path) 252 | (if-let [segs (re-seq #"/([^/]+)" path)] 253 | (if (> (count segs) 1) 254 | (let [parent-path (apply str (map first (take (dec (count segs)) segs))) 255 | parent (get-patch-value obj parent-path)] 256 | (replace-patch-value obj parent-path 257 | (remove-patch-value parent (first (last segs))))) 258 | (cond (map? obj) 259 | (dissoc obj (->key (second (first segs)))) 260 | (vector? obj) 261 | (let [idx #?(:clj (Integer/parseInt (second (re-find #"/(\d+)" path))) 262 | :cljs (js/parseInt (second (re-find #"/(\d+)" path))))] 263 | (vec (concat (subvec obj 0 idx) 264 | [val] 265 | (subvec obj (inc idx))))))) 266 | #?(:clj (throw (Exception. "Patch path must start with '/'")) 267 | :cljs (throw (js/Error. "Patch path must start with '/'")))) 268 | #?(:clj (throw (Exception. (str "Can't replace a value that does not exist at '" path "'."))) 269 | :cljs (throw (js/Error. (str "Can't replace a value that does not exist at '" path "'."))))))) 270 | 271 | (defn remove-patch-value-func 272 | "Remove the value at 'path' from obj." 273 | [obj path] 274 | (let [val (get-patch-value obj path)] 275 | (if (some? val) 276 | (if-let [segs (re-seq #"/([^/]+)" path)] 277 | (if (> (count segs) 1) 278 | (let [parent-path (apply str (map first (take (dec (count segs)) segs))) 279 | parent (get-patch-value obj parent-path)] 280 | (replace-patch-value obj parent-path 281 | (remove-patch-value parent (first (last segs))))) 282 | (cond (map? obj) 283 | (dissoc obj (second (first segs))) 284 | (vector? obj) 285 | (let [idx #?(:clj (Integer/parseInt (second (re-find #"/(\d+)" path))) 286 | :cljs (js/parseInt (second (re-find #"/(\d+)" path))))] 287 | (vec (concat (subvec obj 0 idx) (subvec obj (inc idx)))))))) 288 | #?(:clj (throw (Exception. (str "There is no value at '" path "' to remove."))) 289 | :cljs (throw (js/Error. (str "There is no value at '" path "' to remove."))))))) 290 | 291 | 292 | (defn remove-patch-value 293 | "Remove the value at 'path' from obj." 294 | [obj path] 295 | (try (remove-patch-value-func obj path) 296 | #?(:clj (catch Exception e 297 | (throw (Exception. (str "There is no value at '" path "' to remove.")))) 298 | :cljs (catch js/Object e 299 | (throw (js/Error. (str "There is no value at '" path "' to remove."))))))) 300 | 301 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;; 302 | ;; Works for both clj & cljs 303 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;; 304 | (defn test-patch-value 305 | "Ensure that the value located at 'path' in obj is equal to 'val'." 306 | [obj path val] 307 | (try 308 | (let [value (get-patch-value obj path)] 309 | (if (not= val value) 310 | #?(:clj (throw (Exception. (str "The value is: " (json/generate-string value)))) 311 | :cljs (throw (js/Error. (str "The value is: " (.stringify js/JSON (clj->js value)))))) 312 | obj)) 313 | #?(:clj (catch Exception e 314 | (throw (Exception. 315 | (str "The test failed. " 316 | (json/generate-string val) 317 | " is not found at " path ". " 318 | (.getMessage e))))) 319 | :cljs (catch js/Object e 320 | (throw (js/Error. 321 | (str "The test failed. " 322 | (.stringify js/JSON (clj->js val)) 323 | " is not found at " path ". " 324 | (e.message)))))))) 325 | 326 | (defn apply-patch [obj patch] 327 | "Apply the patch operation in patch to obj, returning the new obj representation." 328 | (let [op (or (get patch "op") 329 | (get patch :op)) 330 | path (or (get patch "path") 331 | (get patch :path)) 332 | from (or (get patch "from") 333 | (get patch :from)) 334 | value (or (get patch "value") 335 | (get patch :value))] 336 | (cond (= "add" op) 337 | (add-patch-value obj path value) 338 | (= "move" op) 339 | (move-patch-value obj from path) 340 | (= "remove" op) 341 | (remove-patch-value obj path) 342 | (= "replace" op) 343 | (replace-patch-value obj path value) 344 | (= "test" op) 345 | (test-patch-value obj path value)))) 346 | 347 | (defn gen-op [t] 348 | [(let [result {"op" (first t) "path" (second t)}] 349 | (if (> (count t) 2) 350 | (assoc result "value" (nth t 2)) 351 | result))]) 352 | 353 | (defn clean-prefix 354 | [prefix path] 355 | (clo-str/replace path (re-pattern prefix) "/")) 356 | 357 | (defn sanitize 358 | [prefix patch] 359 | (let [path (get patch "path") 360 | cleaned-path (assoc patch "path" (clean-prefix prefix path))] 361 | (if-let [from (get patch "from")] 362 | (assoc cleaned-path "from" (clean-prefix prefix from)) 363 | cleaned-path))) 364 | 365 | (defn sanitize-prefix-in-patch 366 | [prefix idx patch] 367 | (if (vector? patch) 368 | (map (partial sanitize (str prefix idx)) patch) 369 | (sanitize prefix patch))) 370 | 371 | (defn diff-vecs [obj1 obj2 prefix] 372 | (loop [v1 obj1 373 | v2 obj2 374 | i 0 375 | ops []] 376 | (cond (and (empty? v1) (empty? v2)) 377 | ops 378 | (and (> (count ops) 0) 379 | (= v2 380 | (reduce 381 | #(apply-patch %1 %2) v1 382 | (map (partial sanitize-prefix-in-patch prefix (dec i)) ops)))) 383 | ops 384 | (= (set v1) (set v2)) 385 | (cond (= i (count v1)) 386 | ops 387 | (= (get v1 i) (get v2 i)) 388 | (recur v1 v2 (inc i) ops) 389 | (not= (get v1 i) (get v2 i)) 390 | (let [moved-idx (first (filter (complement nil?) (map-indexed #(if (= (get v1 i) %2) %1) v2)))] 391 | (recur v1 v2 (inc i) 392 | (conj ops {"op" "move" "from" (str prefix i) "path" (str prefix moved-idx)})))) 393 | (= v1 (rest v2)) 394 | (conj ops (gen-op ["add" (str prefix i) (first v2)])) 395 | (= (rest v1) v2) 396 | (conj ops (gen-op ["remove" (str prefix i)])) 397 | (not= (first v1) (first v2)) 398 | (if (and (map? (first v1)) (map? (first v2))) 399 | (recur (rest v1) (rest v2) (inc i) 400 | (conj ops (diff* (first v1) (first v2) (str prefix i "/")))) 401 | (recur (rest v1) (rest v2) (inc i) 402 | (conj ops (gen-op ["replace" (str prefix i) (first v2)])))) 403 | (and (= (first v1) (first v2)) 404 | (not= (rest v1) (rest v2))) 405 | (recur (rest v1) (rest v2) (inc i) ops)))) 406 | 407 | (defn get-value-path 408 | "Traverses obj, looking for a value that matches val, returns path to value." 409 | ([obj val] (get-value-path obj val "/")) 410 | ([obj val prefix] 411 | (cond (map? obj) 412 | (some identity 413 | (concat 414 | (for [[k v] obj] 415 | (if (= v val) 416 | (str prefix (inject-escape-characters k)) 417 | (if-not (string? v) 418 | (get-value-path v val (str prefix (inject-escape-characters k) "/"))))))) 419 | (vector? obj) 420 | (if-let [idx (some identity (map-indexed #(if (= val %2) %1) obj))] 421 | (str prefix idx) 422 | (map-indexed #(get-value-path %2 val (str prefix %1 "/")) obj))))) 423 | 424 | (defn transform-moves 425 | "Attempt to reconcile add/remove patch entries 426 | to a single move entry" 427 | [obj1 obj2 patch] 428 | (loop [adds (filter #(= "add" (get % "op")) patch) 429 | removes (filter #(= "remove" (get % "op")) patch) 430 | p patch] 431 | (if (or (empty? adds) (empty? removes)) 432 | p 433 | (let [f-add (first adds) 434 | f-path (get f-add "path") 435 | f-val (get f-add "value") 436 | moved (filter #(= f-val (get-patch-value obj1 (get % "path"))) removes)] 437 | (if-let [fmoved (first moved)] 438 | (recur (rest adds) (filter #(not= fmoved %) removes) 439 | (conj (filter #(not= f-add %) (filter #(not= fmoved %) patch)) 440 | {"op" "move" "from" (get fmoved "path") "path" f-path})) 441 | (recur (rest adds) removes p)))))) 442 | -------------------------------------------------------------------------------- /test/clj_json_patch/core_test.clj: -------------------------------------------------------------------------------- 1 | (ns clj-json-patch.core-test 2 | (:require [clojure.test :refer :all] 3 | [clj-json-patch.core :refer :all]) 4 | (:use [midje.sweet])) 5 | 6 | (facts "applying patch" 7 | (let [v ["all" "grass" "cows" "eat" "slowly"] 8 | p [{"from" "/1", "op" "move", "path" "/3"}] 9 | expected ["all" "cows" "eat" "grass" "slowly"]] 10 | (patch v p) => expected)) 11 | 12 | (facts "JSON diff" 13 | (let [obj1 {"foo" "bar"} 14 | obj2 {"foo" "bar"} 15 | patches []] 16 | (fact "No difference" 17 | (diff obj1 obj2) => patches)) 18 | (let [obj1 {"foo" "bar"} 19 | obj2 {"baz" "qux" "foo" "bar"} 20 | patches [{"op" "add" "path" "/baz" "value" "qux"}]] 21 | (fact "Adding an Object Member" 22 | (diff obj1 obj2) => patches)) 23 | (let [obj1 {"foo" ["bar" "baz"]} 24 | obj2 {"foo" ["qux" "bar" "baz"]} 25 | patches [{"op" "add" "path" "/foo/0" "value" "qux"}]] 26 | (fact "Adding an Array Element" 27 | (diff obj1 obj2) => patches)) 28 | (let [obj1 {"foo" ["bar" "baz"]} 29 | obj2 {"foo" ["bar" "qux" "baz"]} 30 | patches [{"op" "add" "path" "/foo/1" "value" "qux"}]] 31 | (fact "Adding a second Array Element" 32 | (diff obj1 obj2) => patches)) 33 | (let [obj1 {"foo" "bar" "baz" "qux"} 34 | obj2 {"foo" "bar"} 35 | patches [{"op" "remove" "path" "/baz"}]] 36 | (fact "Removing an Object Member" 37 | (diff obj1 obj2) => patches)) 38 | (let [obj1 {"foo" ["qux" "bar" "baz"]} 39 | obj2 {"foo" ["bar" "baz"]} 40 | patches [{"op" "remove" "path" "/foo/0"}]] 41 | (fact "Removing first Array Element" 42 | (diff obj1 obj2) => patches)) 43 | (let [obj1 {"foo" ["bar" "qux" "baz"]} 44 | obj2 {"foo" ["bar" "baz"]} 45 | patches [{"op" "remove" "path" "/foo/1"}]] 46 | (fact "Removing subsequent Array Element" 47 | (diff obj1 obj2) => patches)) 48 | (let [obj1 {"foo" ["bar" "baz" "qux"]} 49 | obj2 {"foo" ["bar" "baz"]} 50 | patches [{"op" "remove" "path" "/foo/2"}]] 51 | (fact "Removing subsequent Array Element" 52 | (diff obj1 obj2) => patches)) 53 | (let [obj1 {"foo" "bar" "baz" "qux"} 54 | obj2 {"baz" "boo" "foo" "bar"} 55 | patches [{"op" "replace" "path" "/baz" "value" "boo"}]] 56 | (fact "Replacing a Value" 57 | (diff obj1 obj2) => patches)) 58 | (let [obj1 {"foo" {"bar" "kill me" 59 | "baz" "boo"}} 60 | obj2 {"foo" {"baz" "boo"}} 61 | patches [{"op" "remove" "path" "/foo/bar"}]] 62 | (fact "Removing a Nested Object Member" 63 | (diff obj1 obj2) => patches)) 64 | (let [obj1 {"foo" {"baz" "boo"}} 65 | obj2 {"child" {"grandchild" {}} 66 | "foo" {"baz" "boo"}} 67 | patches [{"op" "add" "path" "/child" "value" {"grandchild" {}}}]] 68 | (fact "Adding a Nested Object Member" 69 | (diff obj1 obj2) => patches)) 70 | (let [obj1 {"foo" {"bar" "baz" 71 | "waldo" "fred"} 72 | "qux" {"corge" "grault"}} 73 | obj2 {"foo" {"bar" "baz"} 74 | "qux" {"corge" "grault" 75 | "thud" "fred"}} 76 | patches [{"op" "move" "from" "/foo/waldo" "path" "/qux/thud"}]] 77 | (fact "Moving a Value" 78 | (diff obj1 obj2) => patches)) 79 | (let [obj1 {"foo" ["all" "grass" "cows" "eat"]} 80 | obj2 {"foo" ["all" "cows" "eat" "grass"]} 81 | patches [{"op" "move" "from" "/foo/1" "path" "/foo/3"}]] 82 | (fact "Moving an Array Element" 83 | (diff obj1 obj2) => patches)) 84 | (let [obj1 {"foo" "bar"} 85 | obj2 {"foo" ["all" "cows" "eat" "grass"]} 86 | patches [{"op" "replace" "path" "/foo" 87 | "value" ["all" "cows" "eat" "grass"]}]] 88 | (fact "Replace a value with an Array Element" 89 | (diff obj1 obj2) => patches)) 90 | (let [obj1 {"key1" nil 91 | "key2" "val2"} 92 | obj2 {"key2" "val2"}] 93 | (fact "nil key vs absent key" 94 | (diff obj1 obj2) => [{"op" "remove", "path" "/key1"}])) 95 | (let [obj1 {"test" {"key1" nil 96 | "key2" "val2"}} 97 | obj2 {"test" {"key2" "val2"}}] 98 | (fact "nil key vs absent key, nested" 99 | (diff obj1 obj2) => [{"op" "remove", "path" "/test/key1"}])) 100 | (let [obj1 {"test" [{"key1" "val1"}]} 101 | obj2 {"test" [{"key1" "val1replaced"}]}] 102 | (fact "object val within a vector replaced" 103 | (diff obj1 obj2) => [{"op" "replace", "path" "/test/0/key1", "value" "val1replaced"}])) 104 | (let [obj1 {"test" [{"key1" nil 105 | "key2" "val2"}]} 106 | obj2 {"test" [{"key2" "val2"}]}] 107 | (fact "nil key vs absent key within a vector" 108 | (diff obj1 obj2) => [{"op" "remove", "path" "/test/0/key1"}]))) 109 | 110 | (facts "Happy path JSON patch" 111 | (let [obj1 {"foo" "bar"} 112 | patches []] 113 | (fact "No change" 114 | (patch obj1 patches) => obj1)) 115 | (let [obj1 {"foo" "bar"} 116 | obj2 {"baz" "qux" "foo" "bar"} 117 | patches [{"op" "add" "path" "/baz" "value" "qux"}]] 118 | (fact "Adding an Object Member" 119 | (patch obj1 patches) => obj2)) 120 | (let [obj1 {"foo" ["bar" "baz"]} 121 | obj2 {"foo" ["qux" "bar" "baz"]} 122 | patches [{"op" "add" "path" "/foo/0" "value" "qux"}]] 123 | (fact "Adding an Array Element" 124 | (patch obj1 patches) => obj2)) 125 | (let [obj1 {"foo" ["bar" "baz"]} 126 | obj2 {"foo" ["bar" "qux" "baz"]} 127 | patches [{"op" "add" "path" "/foo/1" "value" "qux"}]] 128 | (fact "Adding a second Array Element" 129 | (patch obj1 patches) => obj2)) 130 | (let [obj1 {"foo" "bar" "baz" "qux"} 131 | obj2 {"foo" "bar"} 132 | patches [{"op" "remove" "path" "/baz"}]] 133 | (fact "Removing an Object Member" 134 | (patch obj1 patches) => obj2)) 135 | (let [obj1 {"foo" ["qux" "bar" "baz"]} 136 | obj2 {"foo" ["bar" "baz"]} 137 | patches [{"op" "remove" "path" "/foo/0"}]] 138 | (fact "Removing first Array Element" 139 | (patch obj1 patches) => obj2)) 140 | (let [obj1 {"foo" ["bar" "qux" "baz"]} 141 | obj2 {"foo" ["bar" "baz"]} 142 | patches [{"op" "remove" "path" "/foo/1"}]] 143 | (fact "Removing subsequent Array Element" 144 | (patch obj1 patches) => obj2)) 145 | (let [obj1 {"foo" ["bar" "baz" "qux"]} 146 | obj2 {"foo" ["bar" "baz"]} 147 | patches [{"op" "remove" "path" "/foo/2"}]] 148 | (fact "Removing subsequent Array Element" 149 | (patch obj1 patches) => obj2)) 150 | (let [obj1 {"foo" "bar" "baz" "qux"} 151 | obj2 {"baz" "boo" "foo" "bar"} 152 | patches [{"op" "replace" "path" "/baz" "value" "boo"}]] 153 | (fact "Replacing a Value" 154 | (patch obj1 patches) => obj2)) 155 | (let [obj1 {"foo" false "baz" "qux"} 156 | obj2 {"baz" "qux" "foo" true} 157 | patches [{"op" "replace" "path" "/foo" "value" true}]] 158 | (fact "Replacing a boolean false Value" 159 | (patch obj1 patches) => obj2)) 160 | (let [obj1 {"foo" {"bar" "kill me" 161 | "baz" "boo"}} 162 | obj2 {"foo" {"baz" "boo"}} 163 | patches [{"op" "remove" "path" "/foo/bar"}]] 164 | (fact "Removing a Nested Object Member" 165 | (patch obj1 patches) => obj2)) 166 | (let [obj1 {"foo" {"baz" "boo"}} 167 | obj2 {"child" {"grandchild" {}} 168 | "foo" {"baz" "boo"}} 169 | patches [{"op" "add" "path" "/child" "value" {"grandchild" {}}}]] 170 | (fact "Adding a Nested Object Member" 171 | (patch obj1 patches) => obj2)) 172 | (let [obj1 {"foo" ["baz" "boo"]} 173 | obj2 {"foo" ["baz" "boo" "added"]} 174 | patches [{"op" "add" "path" "/foo/2" "value" "added"}]] 175 | (fact "Adding to a nested array" 176 | (patch obj1 patches) => obj2)) 177 | (let [obj1 {"foo" ["baz" "boo"]} 178 | obj2 {"foo" ["baz" "boo" "added"]} 179 | patches [{"op" "add" "path" "/foo/-" "value" "added"}]] 180 | (fact "Adding to the end of a nested array" 181 | (patch obj1 patches) => obj2)) 182 | (let [obj1 {"foo" "bar"} 183 | obj2 {"foo" "bar" "baz" "qux"} 184 | patches [{"op" "add" "path" "/baz" "value" "qux" "xyz" 123}]] 185 | (fact "Ignoring unrecognized elements" 186 | (patch obj1 patches) => obj2)) 187 | (let [obj1 {"foo" "bar"} 188 | patches [{"op" "add" "path" "/baz/bat" "value" "qux"}]] 189 | (fact "Adding to a nonexistent target" 190 | (patch obj1 patches) => (throws Exception "Unable to set value at '/baz/bat'. Consider adding a more explicit data structure as a child of an existing object."))) 191 | (let [obj1 {"foo" {"bar" "baz" 192 | "waldo" "fred"} 193 | "qux" {"corge" "grault"}} 194 | obj2 {"foo" {"bar" "baz"} 195 | "qux" {"corge" "grault" 196 | "thud" "fred"}} 197 | patches [{"op" "move" "from" "/foo/waldo" "path" "/qux/thud"}]] 198 | (fact "Moving a Value" 199 | (patch obj1 patches) => obj2)) 200 | (let [obj1 {"foo" ["all" "grass" "cows" "eat"]} 201 | obj2 {"foo" ["all" "cows" "eat" "grass"]} 202 | patches [{"op" "move" "from" "/foo/1" "path" "/foo/3"}]] 203 | (fact "Moving an Array Element" 204 | (patch obj1 patches) => obj2)) 205 | (let [obj [ "a" 2 "c"] 206 | patches [{ "op" "test" "path" "/1" "value" 2}]] 207 | (fact "Successful test ops return object" 208 | (patch obj patches) => obj)) 209 | (let [obj {"baz" "qux" "foo" [ "a" 2 "c"]} 210 | patches [{ "op" "test" "path" "/baz" "value" "qux"} 211 | { "op" "test" "path" "/foo/1" "value" 2}]] 212 | (fact "Successful test ops return object" 213 | (patch obj patches) => obj)) 214 | (let [obj {"k1" [{"s0k1" "s0v1"} {"s1k1" "s1v1"}]} 215 | patches [{"op" "replace" "path" "/k1/0/s0k1" "value" "new value"}] 216 | patched (patch obj patches)] 217 | (fact "expected patched object" 218 | patched => {"k1" [{"s0k1" "new value"} {"s1k1" "s1v1"}]}) 219 | (fact "first nested object updated correctly" 220 | (get (first (get patched "k1")) "s0k1") => "new value") 221 | (fact "second nested object unchanged" 222 | (get (second (get patched "k1")) "s1k1") => "s1v1")) 223 | (fact "Patch with escape characters" 224 | (patch {"foo" {"bar" 42}} 225 | [{"op" "add", "path" "/foo/baz~1bar", "value" "ohyeah"}]) => {"foo" {"bar" 42 "baz/bar" "ohyeah"}})) 226 | 227 | (facts "Nested JSON patch" 228 | (let [obj1 {"nested" {"foo" "bar"}} 229 | obj2 {"nested" {"foo" "bar" 230 | "zot" "baz"}} 231 | patches [{"op" "add" "path" "/nested/zot" "value" "baz"}]] 232 | (fact "nested object is patched" 233 | (patch obj1 patches) => obj2))) 234 | 235 | (facts "Remove from object within array" 236 | (let [obj1 [{"name" "item1" "foo" "bar"} 237 | {"name" "item2" "foo" "bar"}] 238 | obj2 [{"name" "item1"} 239 | {"name" "item2" "foo" "bar"}] 240 | patches [{"op" "remove" "path" "/0/foo"}]] 241 | (fact "nested object is patched" 242 | (patch obj1 patches) => obj2))) 243 | 244 | (facts "Add to object within array" 245 | (let [obj {"array" [{"id" "hello"}]} 246 | expected {"array" [{"id" "hello" "foo" "bar"}]} 247 | patches [{"op" "add" "path" "/array/0/foo" "value" "bar"}]] 248 | (fact "obj with two keys as only element of array" 249 | (patch obj patches) => expected))) 250 | 251 | (facts "Patch error conditions" 252 | (let [obj1 {"foo" "bar"} 253 | patches [{"op" "test" "path" "/baz" "value" "qux"}]] 254 | (fact "Testing an Object Member" 255 | (patch obj1 patches) => (throws Exception "The test failed. \"qux\" is not found at /baz. The value is: null"))) 256 | (let [obj1 ["foo" "bar"] 257 | patches [{"op" "test" "path" "/4" "value" "qux"}]] 258 | (fact "Testing an Array Member" 259 | (patch obj1 patches) => (throws Exception "The test failed. \"qux\" is not found at /4. "))) 260 | (let [obj1 {"foo" "bar"} 261 | patches [{"op" "remove" "path" "/baz" "value" "qux"}]] 262 | (fact "Removing an Object Member" 263 | (patch obj1 patches) => (throws Exception "There is no value at '/baz' to remove."))) 264 | (let [obj1 {"foo" ["bar" "baz"]} 265 | patches [{"op" "remove" "path" "/foo/6" "value" "qux"}]] 266 | (fact "Removing an Array Element" 267 | (patch obj1 patches) => (throws Exception "There is no value at '/foo/6' to remove."))) 268 | (let [obj1 {"foo" ["bar" "baz"]} 269 | patches [{"op" "add" "path" "/foo/3" "value" "qux"}]] 270 | (fact "Adding a second Array Element" 271 | (patch obj1 patches) => (throws Exception "Unable to set value at 3."))) 272 | (let [obj1 {"foo" "bar" "boo" "qux"} 273 | patches [{"op" "replace" "path" "/baz" "value" "boo"}]] 274 | (fact "Replacing a Value that doesn't exist" 275 | (patch obj1 patches) => (throws Exception "Can't replace a value that does not exist at '/baz'."))) 276 | (let [obj1 {"foo" {"beer" "booze" 277 | "baz" "boo"}} 278 | patches [{"op" "remove" "path" "/foo/bar"}]] 279 | (fact "Removing a nested path that does not exist" 280 | (patch obj1 patches) => (throws Exception "There is no value at '/foo/bar' to remove."))) 281 | (let [obj1 {"foo" {"bar" "baz" 282 | "waldorf" "fred"} 283 | "qux" {"corge" "grault"}} 284 | patches [{"op" "move" "from" "/foo/waldo" "path" "/qux/thud"}]] 285 | (fact "Moving a Value that does not exist" 286 | (patch obj1 patches) => (throws Exception "Move attempted on value that does not exist at '/foo/waldo'."))) 287 | (let [obj1 {"foo" ["all" "grass" "cows" "eat"]} 288 | patches [{"op" "move" "from" "/foo/1" "path" "/foo/-1"}]] 289 | (fact "Moving an Array Element to an illegal value" 290 | (patch obj1 patches) => (throws Exception "Move attempted on value that does not exist at '/-1'."))) 291 | (let [obj1 {"foo" ["all" "grass" "cows" "eat"]} 292 | patches [{"op" "add" "path" "/foo/two"}]] 293 | (fact "Adding an Array Element to an non-number index" 294 | (patch obj1 patches) => (throws Exception "Unable to determine array index from 'two'.")))) 295 | -------------------------------------------------------------------------------- /test/clj_json_patch/rfc6901_test.clj: -------------------------------------------------------------------------------- 1 | (ns clj-json-patch.rfc6901-test 2 | (:require [clojure.test :refer :all] 3 | [clj-json-patch.util :refer :all]) 4 | (:use [midje.sweet])) 5 | 6 | ;;https://tools.ietf.org/html/rfc6901 7 | 8 | (facts "RFC6901" 9 | (let [doc { 10 | "foo" ["bar" "baz"] 11 | "" 0 12 | "a/b" 1 13 | "c%d" 2 14 | "e^f" 3 15 | "g|h" 4 16 | "i\\j" 5 17 | "k\"l" 6 18 | " " 7 19 | "m~n" 8}] 20 | 21 | (facts "basic strings" 22 | (fact "whole doc" 23 | (get-patch-value doc "") => doc) 24 | (fact "/foo" 25 | (get-patch-value doc "/foo") => ["bar" "baz"]) 26 | (fact "/foo/0" 27 | (get-patch-value doc "/foo/0") => "bar") 28 | (fact "/" 29 | (get-patch-value doc "/") => 0) 30 | (fact "/a~1b" 31 | (get-patch-value doc "/a~1b") => 1) 32 | (fact "/c%d" 33 | (get-patch-value doc "/c%d") => 2) 34 | (fact "/e^f" 35 | (get-patch-value doc "/e^f") => 3) 36 | (fact "/g|h" 37 | (get-patch-value doc "/g|h") => 4) 38 | (fact "/i\\j" 39 | (get-patch-value doc "/i\\j") => 5) 40 | (fact "/k\"l" 41 | (get-patch-value doc "/k\"l") => 6) 42 | (fact "/ " 43 | (get-patch-value doc "/ ") => 7) 44 | (fact "/m~0n" 45 | (get-patch-value doc "/m~0n") => 8)) 46 | (facts "fragment identifiers" 47 | (fact "# whole doc" 48 | (get-patch-value doc "#") => doc) 49 | (fact "#/foo" 50 | (get-patch-value doc "#/foo") => ["bar" "baz"]) 51 | (fact "#/foo/0" 52 | (get-patch-value doc "#/foo/0") => "bar") 53 | (fact "#/" 54 | (get-patch-value doc "#/") => 0) 55 | (fact "#/a~1b" 56 | (get-patch-value doc "#/a~1b") => 1) 57 | (fact "#/c%d" 58 | (get-patch-value doc "#/c%d") => 2) 59 | (fact "#/e^f" 60 | (get-patch-value doc "#/e^f") => 3) 61 | (fact "#/g|h" 62 | (get-patch-value doc "#/g|h") => 4) 63 | (fact "#/i\\j" 64 | (get-patch-value doc "#/i\\j") => 5) 65 | (fact "#/k\"l" 66 | (get-patch-value doc "#/k\"l") => 6) 67 | (fact "#/ " 68 | (get-patch-value doc "#/ ") => 7) 69 | (fact "#/m~0n" 70 | (get-patch-value doc "#/m~0n") => 8)))) 71 | -------------------------------------------------------------------------------- /test/clj_json_patch/util_test.clj: -------------------------------------------------------------------------------- 1 | (ns clj-json-patch.util-test 2 | (:require [clojure.test :refer :all] 3 | [clj-json-patch.util :refer :all]) 4 | (:use [midje.sweet])) 5 | 6 | (let [obj1 {"foo" "bar"} 7 | obj2 {"foo" {"bar" "baz"}} 8 | obj3 {"foo" {"bar" {"baz" "deep!"}}} 9 | obj4 ["foo" "bar"] 10 | obj5 {"foo" ["bar" "baz" "last"]} 11 | obj6 {"foo" {"bar" ["baz" "deeper!"]}} 12 | obj7 {"foo/bar" "baz"}] 13 | (facts "get-patch-value" 14 | (fact "get value from simple map" 15 | (get-patch-value obj1 "/foo") => "bar") 16 | (fact "get value from nested map" 17 | (get-patch-value obj2 "/foo/bar") => "baz") 18 | (fact "get value from nested maps" 19 | (get-patch-value obj3 "/foo/bar/baz") => "deep!") 20 | (fact "get value from simple array" 21 | (get-patch-value obj4 "/0") => "foo") 22 | (fact "get value from simple map of array" 23 | (get-patch-value obj5 "/foo/1") => "baz") 24 | (fact "get value from map of map with array" 25 | (get-patch-value obj6 "/foo/bar/1") => "deeper!") 26 | (fact "escape / with ~1" 27 | (get-patch-value obj7 "/foo~1bar") => "baz")) 28 | (facts "get-value-path" 29 | (fact "get path from simple map" 30 | (get-value-path obj1 "bar") => "/foo") 31 | (fact "get path from nested map" 32 | (get-value-path obj2 "baz") => "/foo/bar") 33 | (fact "get path from nested maps" 34 | (get-value-path obj3 "deep!") => "/foo/bar/baz") 35 | (fact "get path from simple array" 36 | (get-value-path obj4 "foo") => "/0") 37 | (fact "get path from simple map of array" 38 | (get-value-path obj5 "baz") => "/foo/1") 39 | (fact "get path from map of map with array" 40 | (get-value-path obj6 "deeper!") => "/foo/bar/1") 41 | (fact "get path from key with /" 42 | (get-value-path obj7 "baz") => "/foo~1bar"))) 43 | 44 | (facts "escaping characters" 45 | (fact "must not depend on ordering" 46 | (eval-escape-characters "~01") => "~1")) 47 | 48 | (facts "diff-vecs" 49 | (let [v1 ["all" "grass" "cows" "eat"] 50 | v2 ["all" "cows" "eat" "grass"]] 51 | (fact "two vectors with same elements in different order are not the same" 52 | (count (diff-vecs v1 v2 "/")) => 1 53 | (diff-vecs v1 v2 "/") => [{"from" "/1", "op" "move", "path" "/3"}]))) 54 | 55 | (facts "apply-patch" 56 | (let [v ["all" "grass" "cows" "eat" "slowly"] 57 | patch {"from" "/1", "op" "move", "path" "/3"} 58 | expected ["all" "cows" "eat" "grass" "slowly"]] 59 | (apply-patch v patch) => expected)) 60 | 61 | (facts "get-patch-value and replace-patch-value" 62 | (let [obj {"k1" [{"s0k1" "s0v1"} {"s1k1" "s1v1"}]} 63 | p {"op" "replace" "path" "/k1/0/s0k1" "value" "new value"} 64 | patched (apply-patch obj p)] 65 | (fact "anticipated retrieval" 66 | (get-patch-value obj "/k1/0/s0k1") => "s0v1" 67 | (get-patch-value obj "/k1/1/s1k1") => "s1v1") 68 | (fact "mutation of object nested in array" 69 | (replace-patch-value obj "/k1/0/s0k1" "new value") 70 | => {"k1" [{"s0k1" "new value"} {"s1k1" "s1v1"}]}) 71 | (fact "first nested object updated correctly" 72 | (get-patch-value patched "/k1/0/s0k1") => "new value") 73 | (fact "second nested object unchanged" 74 | (get-patch-value patched "/k1/1/s1k1") => "s1v1"))) 75 | --------------------------------------------------------------------------------