├── .github └── workflows │ └── test-package.yml ├── .gitignore ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── analysis_options.yaml ├── lib ├── json_diff.dart └── src │ ├── diff_node.dart │ └── json_differ.dart ├── pubspec.yaml └── test ├── atomics_test.dart ├── ignored_test.dart ├── json_diff_test.dart └── test_all_the_things.dart /.github/workflows/test-package.yml: -------------------------------------------------------------------------------- 1 | name: Dart CI 2 | 3 | on: 4 | # Run on PRs and pushes to the default branch. 5 | push: 6 | branches: [ master ] 7 | pull_request: 8 | branches: [ master ] 9 | schedule: 10 | - cron: "0 0 * * 0" 11 | 12 | env: 13 | PUB_ENVIRONMENT: bot.github 14 | 15 | jobs: 16 | # Check code formatting and static analysis on a single OS (linux) 17 | # against Dart dev. 18 | analyze: 19 | runs-on: ubuntu-latest 20 | strategy: 21 | fail-fast: false 22 | matrix: 23 | sdk: [dev] 24 | steps: 25 | - uses: actions/checkout@v2 26 | - uses: dart-lang/setup-dart@v1.0 27 | with: 28 | sdk: ${{ matrix.sdk }} 29 | - id: install 30 | name: Install dependencies 31 | run: dart pub get 32 | - name: Check formatting 33 | run: dart format --output=none --set-exit-if-changed . 34 | if: always() && steps.install.outcome == 'success' 35 | - name: Analyze code 36 | run: dart analyze --fatal-infos 37 | if: always() && steps.install.outcome == 'success' 38 | 39 | # Run tests on a matrix consisting of two dimensions: 40 | # 1. OS: ubuntu-latest, (macos-latest, windows-latest) 41 | # 2. release channel: dev 42 | test: 43 | needs: analyze 44 | runs-on: ${{ matrix.os }} 45 | strategy: 46 | fail-fast: false 47 | matrix: 48 | # Add macos-latest and/or windows-latest if relevant for this package. 49 | os: [ubuntu-latest] 50 | sdk: [2.12.0, dev] 51 | steps: 52 | - uses: actions/checkout@v2 53 | - uses: dart-lang/setup-dart@v1.0 54 | with: 55 | sdk: ${{ matrix.sdk }} 56 | - id: install 57 | name: Install dependencies 58 | run: dart pub get 59 | - name: Run VM tests 60 | run: dart test --platform vm 61 | if: always() && steps.install.outcome == 'success' 62 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | packages/ 3 | bin/packages 4 | test/packages 5 | pubspec.lock 6 | .buildlog 7 | .project 8 | .pub/ 9 | .DS_Store 10 | *.dart.js 11 | *.js_ 12 | *.js.deps 13 | *.js.map 14 | 15 | 16 | # Files and directories created by pub 17 | .dart_tool/ 18 | .packages 19 | 20 | # Directory created by dartdoc 21 | doc/api/ 22 | 23 | # Mac related files 24 | **/.DS_Store 25 | 26 | # IDEA related files 27 | .idea 28 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 0.2.1 2 | 3 | * Bump to diff\_match\_patch ^0.4.1 4 | 5 | ## 0.2.0 6 | 7 | * Migrate to Dart's null safe type system 8 | * Support moved elements in lists 9 | * Fix various bugs for changed lists 10 | * Bump to diff\_match\_patch ^0.3.0 11 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Want to contribute? Great! First, read this page (including the small print at the end). 2 | 3 | ### Before you contribute 4 | 5 | Before we can use your code, you must sign the 6 | [Google Individual Contributor License Agreement](https://developers.google.com/open-source/cla/individual?csw=1) 7 | (CLA), which you can do online. The CLA is necessary mainly because you own the 8 | copyright to your changes, even after your contribution becomes part of our 9 | codebase, so we need your permission to use and distribute your code. We also 10 | need to be sure of various other things—for instance that you'll tell us if you 11 | know that your code infringes on other people's patents. You don't have to sign 12 | the CLA until after you've submitted your code for review and a member has 13 | approved it, but you must do it before we can put your code into our codebase. 14 | 15 | Before you start working on a larger contribution, you should get in touch with 16 | us first through the issue tracker with your idea so that we can help out and 17 | possibly guide you. Coordinating up front makes it much easier to avoid 18 | frustration later on. 19 | 20 | ### Code reviews 21 | 22 | All submissions, including submissions by project members, require review. We 23 | use Github pull requests for this purpose. 24 | 25 | ### The small print 26 | 27 | Contributions made by corporations are covered by a different agreement than 28 | the one above, the Software Grant and Corporate Contributor License Agreement. 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://github.com/google/dart-json_diff/workflows/Dart%20CI/badge.svg)](https://github.com/google/dart-json_diff/actions?query=workflow%3A"Dart+CI"+branch%3Amaster) 2 | 3 | Generate a diff between two JSON strings. 4 | 5 | Usage 6 | ----- 7 | 8 | Here's a basic example which features a deleted object, a new object, a changed 9 | object, and a deeply changed object: 10 | 11 | ```dart 12 | import 'package:json_diff/json_diff.dart'; 13 | 14 | final left = {"a": 2, "b": 3, "c": 5, "d": {"x": 4, "y": 8}}; 15 | final right = {"b": 7, "c": 5, "d": {"x": 4, "z": 16}, "e": 11}; 16 | final differ = JsonDiffer.fromJson(left, right); 17 | DiffNode diff = differ.diff(); 18 | print(diff.added); // => {"e": 11} 19 | print(diff.removed); // => {"a": 2} 20 | print(diff.changed); // => {"b": [3, 7]} 21 | print(diff.node); // => a Map 22 | print(diff.node['d']); // => a DiffNode 23 | print(diff.node['d'].added); // => {"z": 16} 24 | print(diff.node['d'].removed); // => {"y": 8} 25 | ``` 26 | 27 | So that's pretty fun. So when you diff two JSON strings, you get back a 28 | DiffNode. A DiffNode is a heirarchical structure that vaguely mirrors the 29 | structure of the input JSON strings. In this example, the top-level DiffNode we 30 | got back has 31 | 32 | * an `added` property, which is a Map of top-level properties that 33 | were _not_ found in `left`, and _were_ found in `right`. 34 | * a `removed` property, which is a Map of top-level properties that were found 35 | in `left`, but were `not` found in `right`. 36 | * a `changed` property, which is a Map of top-level properties whose values are 37 | different in `left` and in `right`. The values in this Map are two-element 38 | Arrays. The 0th element is the old value (from `left`), and the 1st element 39 | is the new value (from `right`). 40 | * a `moved` property, which is a Map of indexes, where key is the original index 41 | of an element, and value is index in the changed list. 42 | * a `node` property, a Map of the properties found in both `left` and `right` 43 | that have deep differences. The values of this Map are more DiffNodes. 44 | * a `path` property, which is a List of indexes, describing the path from the root 45 | where this DiffNode is operating. 46 | 47 | Contributing 48 | ------------ 49 | 50 | Contributions welcome! Please read the 51 | [contribution guidelines](CONTRIBUTING.md). 52 | 53 | Disclaimer 54 | ---------- 55 | 56 | This is not an official Google product. 57 | -------------------------------------------------------------------------------- /analysis_options.yaml: -------------------------------------------------------------------------------- 1 | include: package:lints/recommended.yaml 2 | 3 | analyzer: 4 | language: 5 | strict-casts: true 6 | strict-inference: true 7 | strict-raw-types: true 8 | 9 | linter: 10 | rules: 11 | - avoid_dynamic_calls 12 | -------------------------------------------------------------------------------- /lib/json_diff.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Google Inc. All Rights Reserved. 2 | // Licensed under the Apache License, Version 2.0, found in the LICENSE file. 3 | 4 | /// A library for determining the difference between two JSON objects. 5 | /// 6 | /// ## Usage 7 | /// 8 | /// In order to diff two JSON objects, stored as Dart strings, create a new 9 | /// [JsonDiffer], passing the two objects: 10 | /// 11 | /// JsonDiffer differ = new JsonDiffer(leftJsonString, rightJsonString) 12 | /// 13 | /// To calculate the diff between the two objects, call `diff()` on the 14 | /// [JsonDiffer], which will return a [DiffNode]: 15 | /// 16 | /// DiffNode diff = differ.diff(); 17 | /// 18 | /// This [DiffNode] object is a hierarchical structure (like JSON) of the 19 | /// differences between the two objects. 20 | library json_diff; 21 | 22 | import 'dart:convert'; 23 | import 'package:collection/collection.dart'; 24 | 25 | part 'src/diff_node.dart'; 26 | part 'src/json_differ.dart'; 27 | -------------------------------------------------------------------------------- /lib/src/diff_node.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Google Inc. All Rights Reserved. 2 | // Licensed under the Apache License, Version 2.0, found in the LICENSE file. 3 | 4 | part of json_diff; 5 | 6 | /// A hierarchical structure representing the differences between two JSON 7 | /// objects. 8 | /// 9 | /// A DiffNode object is returned by [JsonDiffer]'s `diff()` method. DiffNode 10 | /// is a tree structure, referring to more DiffNodes in the `node` property. 11 | /// To access the differences in a DiffNode, refer to the following properties: 12 | /// 13 | /// * [added] is a Map of key-value pairs found in the _right_ JSON but not in 14 | /// the _left_ JSON. 15 | /// * [removed] is a Map of key-value pairs found in the _left_ JSON but not in 16 | /// the _right_ JSON. 17 | /// * [changed] is a Map referencing immediate values that are different 18 | /// between the _left_ and _right_ JSONs. Each key in the Map is a key whose 19 | /// values changed, mapping to a 2-element array which lists the left value 20 | /// and the right value. 21 | /// * [node] is a Map of deeper changes. Each key in this Map is a key whose 22 | /// values changed deeply between the left and right JSONs, mapping to a 23 | /// DiffNode containing those deep changes. 24 | class DiffNode { 25 | DiffNode(this.path); 26 | 27 | /// A Map of deep changes between the two JSON objects. 28 | final node = {}; 29 | 30 | /// A Map containing the key/value pairs that were _added_ between the left 31 | /// JSON and the right. 32 | final added = {}; 33 | 34 | /// A Map containing the key/value pairs that were _removed_ between the left 35 | /// JSON and the right. 36 | final removed = {}; 37 | 38 | /// A Map whose values are 2-element arrays containing the left value and the 39 | /// right value, corresponding to the mapping key. 40 | final Map> changed = >{}; 41 | 42 | /// A Map of _moved_ elements in the List, where the key is the original 43 | /// position, and the value is the new position. 44 | final moved = {}; 45 | 46 | /// The path, starting from the root, where this [DiffNode] is describing the 47 | /// left and right JSON, e.g. ["propertyA", 1, "propertyB"]. 48 | final List path; 49 | 50 | /// A convenience method for `node[]=`. 51 | void operator []=(Object s, DiffNode d) { 52 | node[s] = d; 53 | } 54 | 55 | /// A convenience method for `node[]`. 56 | DiffNode? operator [](Object s) { 57 | return node[s]; 58 | } 59 | 60 | /// A convenience method for `node.containsKey()`. 61 | bool containsKey(Object s) { 62 | return node.containsKey(s); 63 | } 64 | 65 | void forEach(void Function(Object s, DiffNode dn) ffn) => node.forEach(ffn); 66 | 67 | List map(void Function(Object s, DiffNode dn) ffn) { 68 | final result = []; 69 | forEach((s, dn) { 70 | result.add(ffn(s, dn)); 71 | }); 72 | return result; 73 | } 74 | 75 | void forEachOf(String key, void Function(Object s, DiffNode dn) ffn) { 76 | if (node.containsKey(key)) { 77 | node[key]!.forEach(ffn); 78 | } 79 | } 80 | 81 | void forEachAdded(void Function(Object s, Object? o) ffn) => 82 | added.forEach(ffn); 83 | 84 | void forEachRemoved(void Function(Object s, Object? o) ffn) => 85 | removed.forEach(ffn); 86 | 87 | void forEachChanged(void Function(Object s, List o) ffn) => 88 | changed.forEach(ffn); 89 | 90 | void forAllAdded(void Function(Object? _, Object? o) ffn, 91 | {Map root = const {}}) { 92 | added.forEach((key, thisNode) => ffn(root, thisNode)); 93 | node.forEach((key, node) { 94 | root[key] = {}; 95 | node.forAllAdded((addedMap, root) => ffn(root, addedMap), 96 | root: root[key] as Map); 97 | }); 98 | } 99 | 100 | Map? allAdded() { 101 | final thisNode = {}; 102 | added.forEach((k, v) { 103 | thisNode[k] = v; 104 | }); 105 | node.forEach((k, v) { 106 | final down = v.allAdded(); 107 | if (down == null) { 108 | return; 109 | } 110 | thisNode[k] = down; 111 | }); 112 | 113 | if (thisNode.isEmpty) { 114 | return null; 115 | } 116 | return thisNode; 117 | } 118 | 119 | bool get hasAdded => added.isNotEmpty; 120 | bool get hasRemoved => removed.isNotEmpty; 121 | bool get hasChanged => changed.isNotEmpty; 122 | bool get hasMoved => moved.isNotEmpty; 123 | bool get hasNothing => 124 | added.isEmpty && 125 | removed.isEmpty && 126 | changed.isEmpty && 127 | moved.isEmpty && 128 | node.isEmpty; 129 | 130 | /// Prunes the DiffNode tree. 131 | /// 132 | /// If a child DiffNode has nothing added, removed, changed, nor a node, then it will 133 | /// be deleted from the parent's [node] Map. 134 | void prune() { 135 | var keys = node.keys.toList(); 136 | for (var i = keys.length - 1; i >= 0; i--) { 137 | final key = keys[i]; 138 | final d = node[key]!; 139 | d.prune(); 140 | if (d.hasNothing) { 141 | node.remove(key); 142 | } 143 | } 144 | } 145 | 146 | @override 147 | String toString() => _diffToString(this).join('\n'); 148 | } 149 | 150 | List _diffToString(DiffNode diff) => [ 151 | for (final e in diff.removed.entries) ...[ 152 | '@ Removed from left at path "${[...diff.path, e.key]}":', 153 | '- ${jsonEncode(e.value)}', 154 | ], 155 | for (final e in diff.added.entries) ...[ 156 | '@ Added to right at path "${[...diff.path, e.key]}":', 157 | '+ ${jsonEncode(e.value)}' 158 | ], 159 | for (final e in diff.changed.entries) ...[ 160 | '@ Changed at path "${[...diff.path, e.key]}":', 161 | '- ${jsonEncode(e.value.first)}', 162 | '+ ${jsonEncode(e.value.last)}', 163 | ], 164 | for (final e in diff.moved.entries) ...[ 165 | '@ Moved at path "${[...diff.path, e.key]}"', 166 | '${e.key} -> ${e.value}' 167 | ], 168 | for (final e in diff.node.entries) ..._diffToString(e.value) 169 | ]; 170 | -------------------------------------------------------------------------------- /lib/src/json_differ.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Google Inc. All Rights Reserved. 2 | // Licensed under the Apache License, Version 2.0, found in the LICENSE file. 3 | 4 | part of json_diff; 5 | 6 | /// A configurable class that can produce a diff of two JSON Strings. 7 | class JsonDiffer { 8 | final Object leftJson, rightJson; 9 | final List atomics = []; 10 | final List ignored = []; 11 | 12 | /// Constructs a new JsonDiffer using [leftString] and [rightString], two 13 | /// JSON objects represented as Dart strings. 14 | /// 15 | /// If the two JSON objects that need to be diffed are only available as 16 | /// Dart Maps, you can use the 17 | /// [dart:convert](https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart:convert) 18 | /// library to encode each Map into a JSON String. 19 | JsonDiffer( 20 | String leftString, 21 | String rightString, 22 | ) : leftJson = jsonDecode(leftString) as Object, 23 | rightJson = jsonDecode(rightString) as Object; 24 | 25 | JsonDiffer.fromJson(this.leftJson, this.rightJson); 26 | 27 | /// Compare the two JSON Strings, producing a [DiffNode]. 28 | /// 29 | /// The differ will walk the entire object graph of each JSON object, 30 | /// tracking all additions, deletions, and changes. Please see the 31 | /// documentation for [DiffNode] to understand how to access the differences 32 | /// found between the two JSON Strings. 33 | DiffNode diff() { 34 | if (leftJson is Map && rightJson is Map) { 35 | return _diffObjects( 36 | (leftJson as Map).cast(), 37 | (rightJson as Map).cast(), 38 | [], 39 | )..prune(); 40 | } else if (leftJson is List && rightJson is List) { 41 | return _diffLists((leftJson as List).cast(), 42 | (rightJson as List).cast(), null, []); 43 | } 44 | return DiffNode([])..changed[''] = [leftJson, rightJson]; 45 | } 46 | 47 | DiffNode _diffObjects(Map left, Map right, 48 | List path) { 49 | final node = DiffNode(path); 50 | left.forEach((String key, Object? leftValue) { 51 | if (ignored.contains(key)) { 52 | return; 53 | } 54 | 55 | if (!right.containsKey(key)) { 56 | // key is missing from right. 57 | node.removed[key] = leftValue; 58 | return; 59 | } 60 | 61 | final rightValue = right[key]; 62 | if (atomics.contains(key) && 63 | leftValue.toString() != rightValue.toString()) { 64 | // Treat [leftValue] and [rightValue] as atomic objects, even if they 65 | // are deep maps or some such thing. 66 | node.changed[key] = [leftValue, rightValue]; 67 | } else if (leftValue is List && rightValue is List) { 68 | node[key] = _diffLists(leftValue.cast(), 69 | rightValue.cast(), key, [...path, key]); 70 | } else if (leftValue is Map && rightValue is Map) { 71 | node[key] = _diffObjects(leftValue.cast(), 72 | rightValue.cast(), [...path, key]); 73 | } else if (leftValue != rightValue) { 74 | // value is different between [left] and [right]. 75 | node.changed[key] = [leftValue, rightValue]; 76 | } 77 | }); 78 | 79 | right.forEach((String key, Object? value) { 80 | if (ignored.contains(key)) { 81 | return; 82 | } 83 | 84 | if (!left.containsKey(key)) { 85 | // key is missing from left. 86 | node.added[key] = value; 87 | } 88 | }); 89 | 90 | return node; 91 | } 92 | 93 | bool _deepEquals(Object? e1, Object? e2) => 94 | DeepCollectionEquality.unordered().equals(e1, e2); 95 | 96 | DiffNode _diffLists(List left, List right, 97 | String? parentKey, List path) { 98 | final node = DiffNode(path); 99 | var leftHand = 0; 100 | var leftFoot = 0; 101 | var rightHand = 0; 102 | var rightFoot = 0; 103 | while (leftFoot < left.length && rightFoot < right.length) { 104 | if (!_deepEquals(left[leftFoot], right[rightFoot])) { 105 | var foundMissing = false; 106 | // Walk hands up one at a time. Feet keep track of where we were. 107 | while (true) { 108 | rightHand++; 109 | if (rightHand < right.length && 110 | _deepEquals(left[leftFoot], right[rightHand])) { 111 | // Found it: the right elements at [rightFoot, rightHand-1] were added in right. 112 | for (var i = rightFoot; i < rightHand; i++) { 113 | node.added[i] = right[i]; 114 | } 115 | rightFoot = rightHand; 116 | leftHand = leftFoot; 117 | foundMissing = true; 118 | break; 119 | } 120 | 121 | leftHand++; 122 | if (leftHand < left.length && 123 | _deepEquals(left[leftHand], right[rightFoot])) { 124 | // Found it: The left elements at [leftFoot, leftHand-1] were removed from left. 125 | for (var i = leftFoot; i < leftHand; i++) { 126 | node.removed[i] = left[i]; 127 | } 128 | leftFoot = leftHand; 129 | rightHand = rightFoot; 130 | foundMissing = true; 131 | break; 132 | } 133 | 134 | if (leftHand >= left.length && rightHand >= right.length) { 135 | break; 136 | } 137 | } 138 | 139 | if (!foundMissing) { 140 | // Never found `left[leftFoot]` in [right], nor `right[rightFoot]` in 141 | // [left]. This must just be a changed value. 142 | // TODO: This notation is wrong for a case such as: 143 | // [1,2,3,4,5,6] => [1,4,5,7] 144 | // changed.first = [[5, 6], [3,7] 145 | final leftObject = left[leftFoot]; 146 | final rightObject = right[rightFoot]; 147 | if (parentKey != null && 148 | atomics.contains('$parentKey[]') && 149 | leftObject.toString() != rightObject.toString()) { 150 | // Treat leftValue and rightValue as atomic objects, even if they are 151 | // deep maps or some such thing. 152 | node.changed[leftFoot] = [leftObject, rightObject]; 153 | } else if (leftObject is Map && rightObject is Map) { 154 | node[leftFoot] = _diffObjects(leftObject.cast(), 155 | rightObject.cast(), [...path, leftFoot]); 156 | } else if (leftObject is List && rightObject is List) { 157 | node[leftFoot] = _diffLists(leftObject.cast(), 158 | rightObject.cast(), null, [...path, leftFoot]); 159 | } else { 160 | node.changed[leftFoot] = [leftObject, rightObject]; 161 | } 162 | } 163 | } 164 | leftHand++; 165 | rightHand++; 166 | leftFoot++; 167 | rightFoot++; 168 | } 169 | 170 | // Any new elements at the end of right. 171 | for (var i = rightFoot; i < right.length; i++) { 172 | node.added[i] = right[i]; 173 | } 174 | 175 | // Any removed elements at the end of left. 176 | for (var i = leftFoot; i < left.length; i++) { 177 | node.removed[i] = left[i]; 178 | } 179 | 180 | // Equal elements that both exist in added 181 | // and removed can be considered moved 182 | final removedFiltered = node.removed.entries.where((e) { 183 | final added = node.added 184 | .removeFirstWhere((key, value) => _deepEquals(e.value, value)); 185 | 186 | if (added != null) { 187 | // We've found an equal element in [added], put the element in 188 | // `node.moved` and filtered it out from `node.removed`. 189 | node.moved[e.key as int] = added.key as int; 190 | return false; 191 | } 192 | 193 | // Element is not present in [added]; it is simply removed. 194 | return true; 195 | }).toList(); 196 | 197 | node.removed.clear(); 198 | node.removed.addEntries(removedFiltered); 199 | 200 | return node; 201 | } 202 | } 203 | 204 | /// An exception that is thrown when two JSON Strings did not pass a basic sanity test. 205 | class UncomparableJsonException implements Exception { 206 | final String msg; 207 | 208 | const UncomparableJsonException(this.msg); 209 | 210 | @override 211 | String toString() => 'UncomparableJsonException: $msg'; 212 | } 213 | 214 | extension on Map { 215 | MapEntry? removeFirstWhere(bool Function(K, V) test) { 216 | for (final entry in entries) { 217 | if (test(entry.key, entry.value)) { 218 | remove(entry.key); 219 | return entry; 220 | } 221 | } 222 | 223 | return null; 224 | } 225 | } 226 | -------------------------------------------------------------------------------- /pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: json_diff 2 | version: 0.2.1 3 | description: Utilities for diffing two JSON objects 4 | homepage: https://github.com/google/dart-json_diff 5 | 6 | environment: 7 | sdk: '>=2.12.0 <3.0.0' 8 | dependencies: 9 | collection: ^1.14.13 10 | diff_match_patch: ^0.4.1 11 | dev_dependencies: 12 | lints: ^2.0.0 13 | test: ^1.6.4 14 | 15 | -------------------------------------------------------------------------------- /test/atomics_test.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2015 Google Inc. All Rights Reserved. 2 | // Licensed under the Apache License, Version 2.0, found in the LICENSE file. 3 | 4 | /// Unit tests for json_diff's atomics feature. 5 | library atomics_tests; 6 | 7 | import 'package:json_diff/json_diff.dart'; 8 | import 'package:test/test.dart'; 9 | 10 | void main() { 11 | JsonDiffer differ; 12 | 13 | test('JsonDiffer keeps changed top-level atomics whole', () { 14 | differ = JsonDiffer('{"a": {"x": 1}}', '{"a": {"x": 2}}'); 15 | differ.atomics.add('a'); 16 | final node = differ.diff(); 17 | expect(node.added, isEmpty); 18 | expect(node.removed, isEmpty); 19 | expect(node.changed, hasLength(1)); 20 | expect( 21 | node.changed['a'], 22 | equals([ 23 | {'x': 1}, 24 | {'x': 2} 25 | ])); 26 | }); 27 | 28 | test('JsonDiffer keeps new top-level atomics whole', () { 29 | differ = JsonDiffer('{}', '{"a": {"x": 2}}'); 30 | differ.atomics.add('a'); 31 | final node = differ.diff(); 32 | expect(node.removed, isEmpty); 33 | expect(node.changed, isEmpty); 34 | expect(node.added, hasLength(1)); 35 | expect( 36 | node.added, 37 | equals({ 38 | 'a': {'x': 2} 39 | })); 40 | }); 41 | 42 | test('JsonDiffer keeps removed top-level atomics whole', () { 43 | differ = JsonDiffer('{"a": {"x": 1}}', '{}'); 44 | differ.atomics.add('a'); 45 | final node = differ.diff(); 46 | expect(node.changed, isEmpty); 47 | expect(node.added, isEmpty); 48 | expect(node.removed, hasLength(1)); 49 | expect( 50 | node.removed, 51 | equals({ 52 | 'a': {'x': 1} 53 | })); 54 | }); 55 | 56 | test('JsonDiffer doesn\'t treat unchanged atomics differently', () { 57 | differ = JsonDiffer('{"a": {"x": 1}}', '{"a": {"x": 1}}'); 58 | differ.atomics.add('a'); 59 | final node = differ.diff(); 60 | expect(node.added, isEmpty); 61 | expect(node.removed, isEmpty); 62 | expect(node.changed, isEmpty); 63 | }); 64 | 65 | test('JsonDiffer keeps various atomics whole', () { 66 | differ = JsonDiffer('{"a": {"x": {"y": {"z": 1}}, "y": {"z": 3}}}', 67 | '{"a": {"x": {"y": {"z": 2}}, "y": {"z": 4}}}'); 68 | differ.atomics.add('y'); 69 | final node = differ.diff(); 70 | expect(node.added, isEmpty); 71 | expect(node.removed, isEmpty); 72 | expect(node.changed, isEmpty); 73 | expect(node.node, hasLength(1)); 74 | 75 | var innerNode = node.node['a']!; 76 | expect(innerNode.changed, hasLength(1)); 77 | expect( 78 | innerNode.changed['y'], 79 | equals([ 80 | {'z': 3}, 81 | {'z': 4} 82 | ])); 83 | 84 | innerNode = node.node['a']!['x']!; 85 | expect(innerNode.changed, hasLength(1)); 86 | expect( 87 | innerNode.changed['y'], 88 | equals([ 89 | {'z': 1}, 90 | {'z': 2} 91 | ])); 92 | }); 93 | } 94 | -------------------------------------------------------------------------------- /test/ignored_test.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2015 Google Inc. All Rights Reserved. 2 | // Licensed under the Apache License, Version 2.0, found in the LICENSE file. 3 | 4 | /// Unit tests for json_diff's ignored feature. 5 | library ignored_tests; 6 | 7 | import 'package:json_diff/json_diff.dart'; 8 | import 'package:test/test.dart'; 9 | 10 | void main() { 11 | JsonDiffer differ; 12 | 13 | test('JsonDiffer ignores ignored and changed object keys', () { 14 | differ = JsonDiffer('{"a": {"x": 1}}', '{"a": {"x": 2}}'); 15 | differ.ignored.add('x'); 16 | final node = differ.diff(); 17 | expect(node.added, isEmpty); 18 | expect(node.removed, isEmpty); 19 | expect(node.changed, isEmpty); 20 | expect(node.node, isEmpty); 21 | }); 22 | 23 | test('JsonDiffer ignores ignored and new object keys', () { 24 | differ = JsonDiffer('{"a": {}}', '{"a": {"x": 2}}'); 25 | differ.ignored.add('x'); 26 | final node = differ.diff(); 27 | expect(node.added, isEmpty); 28 | expect(node.removed, isEmpty); 29 | expect(node.changed, isEmpty); 30 | expect(node.node, isEmpty); 31 | }); 32 | 33 | test('JsonDiffer ignores ignored and removed object keys', () { 34 | differ = JsonDiffer('{"a": {"x": 1}}', '{"a": {}}'); 35 | differ.ignored.add('x'); 36 | final node = differ.diff(); 37 | expect(node.added, isEmpty); 38 | expect(node.removed, isEmpty); 39 | expect(node.changed, isEmpty); 40 | expect(node.node, isEmpty); 41 | }); 42 | } 43 | -------------------------------------------------------------------------------- /test/json_diff_test.dart: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Google Inc. All Rights Reserved. 2 | // Licensed under the Apache License, Version 2.0, found in the LICENSE file. 3 | 4 | /// Unit tests for json_diff. 5 | library json_diff_tests; 6 | 7 | import 'package:json_diff/json_diff.dart'; 8 | import 'package:test/test.dart'; 9 | 10 | void main() { 11 | JsonDiffer differ; 12 | 13 | test('JsonDiffer throws FormatException', () { 14 | expect(() => JsonDiffer('{', '{}'), throwsFormatException); 15 | expect(() => JsonDiffer('', ''), throwsFormatException); 16 | }); 17 | 18 | test('JsonDiffer diff() identical objects', () { 19 | differ = JsonDiffer('{"a": 1}', '{"a": 1}'); 20 | final node = differ.diff(); 21 | expect(node.added, isEmpty); 22 | expect(node.removed, isEmpty); 23 | expect(node.changed, isEmpty); 24 | expect(node.node, isEmpty); 25 | }); 26 | 27 | test('JsonDiffer diff() identical lists', () { 28 | differ = JsonDiffer.fromJson([1, 2, null], [1, 2, null]); 29 | final node = differ.diff(); 30 | expect(node.added, isEmpty); 31 | expect(node.removed, isEmpty); 32 | expect(node.changed, isEmpty); 33 | expect(node.node, isEmpty); 34 | }); 35 | 36 | test('JsonDiffer diff() comparing a list and a map', () { 37 | final differ = JsonDiffer.fromJson([1, 2], {'foo': 'bar'}); 38 | final node = differ.diff(); 39 | expect(node.added, isEmpty); 40 | expect(node.removed, isEmpty); 41 | expect(node.changed[''], [ 42 | [1, 2], 43 | {'foo': 'bar'} 44 | ]); 45 | expect(node.node, isEmpty); 46 | }); 47 | 48 | test('JsonDiffer diff() with a new value', () { 49 | differ = JsonDiffer('{"a": 1}', '{"a": 1, "b": null}'); 50 | final node = differ.diff(); 51 | expect(node.added, hasLength(1)); 52 | expect(node.added['b'], equals(null)); 53 | expect(node.removed, isEmpty); 54 | expect(node.changed, isEmpty); 55 | expect(node.node, isEmpty); 56 | }); 57 | 58 | test('JsonDiffer diff() lists with a new value', () { 59 | differ = JsonDiffer.fromJson([1, 2, 3], [1, 2, 3, 4]); 60 | final node = differ.diff(); 61 | expect(node.added[3], equals(4)); 62 | expect(node.removed, isEmpty); 63 | expect(node.changed, isEmpty); 64 | expect(node.node, isEmpty); 65 | }); 66 | 67 | test('JsonDiffer diff() lists with a new null value', () { 68 | differ = JsonDiffer.fromJson([1, 2, 3], [1, 2, 3, null]); 69 | final node = differ.diff(); 70 | expect(node.added[3], equals(null)); 71 | expect(node.removed, isEmpty); 72 | expect(node.changed, isEmpty); 73 | expect(node.node, isEmpty); 74 | }); 75 | 76 | test('JsonDiffer diff() with a deep new value', () { 77 | differ = JsonDiffer('{"a": {"x": 1}}', '{"a": {"x": 1, "y": {"p": 2}}}'); 78 | final node = differ.diff(); 79 | expect(node.added, isEmpty); 80 | expect(node.removed, isEmpty); 81 | expect(node.changed, isEmpty); 82 | expect(node.node, hasLength(1)); 83 | expect(node.node['a']!.added, hasLength(1)); 84 | expect(node.node['a']!.added['y'], equals({'p': 2})); 85 | expect(node.node['a']!.removed, isEmpty); 86 | expect(node.node['a']!.changed, isEmpty); 87 | }); 88 | 89 | test('JsonDiffer diff() with a removed value', () { 90 | differ = JsonDiffer('{"a": 1, "b": 2}', '{"a": 1}'); 91 | final node = differ.diff(); 92 | expect(node.added, isEmpty); 93 | expect(node.removed, hasLength(1)); 94 | expect(node.removed['b'], equals(2)); 95 | expect(node.changed, isEmpty); 96 | expect(node.node, isEmpty); 97 | }); 98 | 99 | test('JsonDiffer diff() lists with a removed value', () { 100 | differ = JsonDiffer.fromJson([1, 2, 3, 4], [1, 2, 3]); 101 | final node = differ.diff(); 102 | expect(node.added, isEmpty); 103 | expect(node.removed[3], equals(4)); 104 | expect(node.changed, isEmpty); 105 | expect(node.node, isEmpty); 106 | }); 107 | 108 | test('JsonDiffer diff() lists with a removed null value', () { 109 | differ = JsonDiffer.fromJson([1, 2, 3, null], [1, 2, 3]); 110 | final node = differ.diff(); 111 | expect(node.added, isEmpty); 112 | expect(node.removed[3], equals(null)); 113 | expect(node.changed, isEmpty); 114 | expect(node.node, isEmpty); 115 | }); 116 | 117 | test('JsonDiffer diff() with a changed value', () { 118 | differ = JsonDiffer('{"a": 1}', '{"a": 2}'); 119 | final node = differ.diff(); 120 | expect(node.added, isEmpty); 121 | expect(node.removed, isEmpty); 122 | expect(node.changed, hasLength(1)); 123 | expect(node.changed['a'], equals([1, 2])); 124 | expect(node.node, isEmpty); 125 | }); 126 | 127 | test('JsonDiffer diff() with a changed value, to null', () { 128 | differ = JsonDiffer('{"a": 1}', '{"a": null}'); 129 | final node = differ.diff(); 130 | expect(node.added, isEmpty); 131 | expect(node.removed, isEmpty); 132 | expect(node.changed, hasLength(1)); 133 | expect(node.changed['a'], equals([1, null])); 134 | expect(node.node, isEmpty); 135 | }); 136 | 137 | test('JsonDiffer diff() lists with a changed value', () { 138 | differ = JsonDiffer.fromJson([1, 2, 3, 4], [1, 2, 9, 4]); 139 | final node = differ.diff(); 140 | expect(node.added, isEmpty); 141 | expect(node.removed, isEmpty); 142 | expect(node.changed[2], equals([3, 9])); 143 | expect(node.node, isEmpty); 144 | }); 145 | 146 | test('JsonDiffer diff() with a deeply changed value', () { 147 | differ = JsonDiffer('{"a": {"x": 1}}', '{"a": {"x": 2}}'); 148 | final node = differ.diff(); 149 | expect(node.added, isEmpty); 150 | expect(node.removed, isEmpty); 151 | expect(node.changed, isEmpty); 152 | expect(node.node, hasLength(1)); 153 | final innerNode = node.node['a']!; 154 | expect(innerNode.changed, hasLength(1)); 155 | expect(innerNode.changed['x'], equals([1, 2])); 156 | }); 157 | 158 | test('JsonDiffer diff() with a new value at the end of a list', () { 159 | differ = JsonDiffer('{"a": [1,2]}', '{"a": [1,2,4]}'); 160 | final node = differ.diff(); 161 | expect(node.added, isEmpty); 162 | expect(node.removed, isEmpty); 163 | expect(node.changed, isEmpty); 164 | expect(node.node, hasLength(1)); 165 | expect(node.node['a']!.added, hasLength(1)); 166 | expect(node.node['a']!.added[2], equals(4)); 167 | expect(node.node['a']!.removed, isEmpty); 168 | expect(node.node['a']!.changed, isEmpty); 169 | }); 170 | 171 | test('JsonDiffer diff() with a new value in the middle of a list', () { 172 | differ = JsonDiffer('{"a": [1,2]}', '{"a": [1,4,2]}'); 173 | final node = differ.diff(); 174 | expect(node.added, isEmpty); 175 | expect(node.removed, isEmpty); 176 | expect(node.changed, isEmpty); 177 | expect(node.node, hasLength(1)); 178 | expect(node.node['a']!.added, hasLength(1)); 179 | expect(node.node['a']!.added[1], equals(4)); 180 | expect(node.node['a']!.removed, isEmpty); 181 | expect(node.node['a']!.changed, isEmpty); 182 | }); 183 | 184 | test('JsonDiffer diff() with multiple new values in the middle of a list', 185 | () { 186 | differ = JsonDiffer('{"a": [1,2]}', '{"a": [1,4,8,2]}'); 187 | final node = differ.diff(); 188 | expect(node.added, isEmpty); 189 | expect(node.removed, isEmpty); 190 | expect(node.changed, isEmpty); 191 | expect(node.node, hasLength(1)); 192 | expect(node.node['a']!.added, hasLength(2)); 193 | expect(node.node['a']!.added[1], equals(4)); 194 | expect(node.node['a']!.added[2], equals(8)); 195 | expect(node.node['a']!.removed, isEmpty); 196 | expect(node.node['a']!.changed, isEmpty); 197 | }); 198 | 199 | test('JsonDiffer diff() with a new value at the start of a list', () { 200 | differ = JsonDiffer('{"a": [1,2]}', '{"a": [4,1,2]}'); 201 | final node = differ.diff(); 202 | expect(node.added, isEmpty); 203 | expect(node.removed, isEmpty); 204 | expect(node.changed, isEmpty); 205 | expect(node.node, hasLength(1)); 206 | expect(node.node['a']!.added, hasLength(1)); 207 | expect(node.node['a']!.added[0], equals(4)); 208 | expect(node.node['a']!.removed, isEmpty); 209 | expect(node.node['a']!.changed, isEmpty); 210 | }); 211 | 212 | test('JsonDiffer diff() with a new object at the start of a list', () { 213 | differ = JsonDiffer( 214 | '{"a": [{"x":1},{"y":2}]}', '{"a": [{"z":4},{"x":1},{"y":2}]}'); 215 | final node = differ.diff(); 216 | expect(node.added, isEmpty); 217 | expect(node.removed, isEmpty); 218 | expect(node.changed, isEmpty); 219 | expect(node.node, hasLength(1)); 220 | expect(node.node['a']!.added, hasLength(1)); 221 | expect(node.node['a']!.added[0], equals({'z': 4})); 222 | expect(node.node['a']!.removed, isEmpty); 223 | expect(node.node['a']!.changed, isEmpty); 224 | }); 225 | 226 | test('JsonDiffer diff() with multiple new values at the start of a list', () { 227 | differ = JsonDiffer('{"a": [1,2]}', '{"a": [4,8,1,2]}'); 228 | final node = differ.diff(); 229 | expect(node.added, isEmpty); 230 | expect(node.removed, isEmpty); 231 | expect(node.changed, isEmpty); 232 | expect(node.node, hasLength(1)); 233 | expect(node.node['a']!.added, hasLength(2)); 234 | expect(node.node['a']!.added[0], equals(4)); 235 | expect(node.node['a']!.added[1], equals(8)); 236 | expect(node.node['a']!.removed, isEmpty); 237 | expect(node.node['a']!.changed, isEmpty); 238 | }); 239 | 240 | test('JsonDiffer diff() with a changed value at the start of a list', () { 241 | differ = JsonDiffer.fromJson({ 242 | 'a': [ 243 | {'b': 1} 244 | ] 245 | }, { 246 | 'a': [ 247 | {'b': 2} 248 | ] 249 | }); 250 | final node = differ.diff(); 251 | expect(node.added, isEmpty); 252 | expect(node.removed, isEmpty); 253 | expect(node.changed, isEmpty); 254 | expect(node.node, hasLength(1)); 255 | expect(node.node['a']!.added, isEmpty); 256 | expect(node.node['a']!.removed, isEmpty); 257 | expect(node.node['a']!.changed, isEmpty); 258 | expect(node.node['a']!.node[0]!.changed, hasLength(1)); 259 | expect(node.node['a']!.node[0]!.changed['b'], equals([1, 2])); 260 | }); 261 | 262 | test( 263 | 'JsonDiffer diff() with multiple changed values at different indexes of a list', 264 | () { 265 | final node = JsonDiffer.fromJson({ 266 | 'primary': [ 267 | { 268 | 'resolvers': [ 269 | 'foo', 270 | ], 271 | }, 272 | { 273 | 'resolvers': [ 274 | 'same on both', 275 | ], 276 | }, 277 | ], 278 | }, { 279 | 'primary': [ 280 | { 281 | 'resolvers': [ 282 | 'bar', 283 | ], 284 | }, 285 | { 286 | 'resolvers': [ 287 | 'same on both', 288 | 'added', 289 | ], 290 | }, 291 | ], 292 | }).diff(); 293 | 294 | expect(node.node['primary']!.node[0]!.node['resolvers']!.changed[0], 295 | equals(['foo', 'bar'])); 296 | expect(node.node['primary']!.node[1]!.node['resolvers']!.added[1], 297 | equals('added')); 298 | }); 299 | 300 | test('JsonDiffer diff() with added element after changed element', () { 301 | const left = { 302 | 'field': [1] 303 | }; 304 | 305 | const right = { 306 | 'field': [2, 'added'] 307 | }; 308 | 309 | final node = JsonDiffer.fromJson(left, right).diff(); 310 | 311 | expect(node.node['field']!.changed[0], equals([1, 2])); 312 | expect(node.node['field']!.added[1], equals('added')); 313 | }); 314 | 315 | test('JsonDiffer diff() with complex elements moved in list', () { 316 | final node = JsonDiffer.fromJson({ 317 | 'list': [ 318 | 'xxx', 319 | 'xxx', 320 | {'foo': 1}, 321 | [2], 322 | ], 323 | }, { 324 | 'list': [ 325 | [2], 326 | {'foo': 1}, 327 | 'xxx', 328 | 'xxx', 329 | ], 330 | }).diff(); 331 | 332 | expect(node.node['list']!.moved[2], equals(1)); 333 | expect(node.node['list']!.moved[3], equals(0)); 334 | }); 335 | } 336 | -------------------------------------------------------------------------------- /test/test_all_the_things.dart: -------------------------------------------------------------------------------- 1 | import 'package:test/test.dart'; 2 | 3 | import 'atomics_test.dart' as atomics_test; 4 | import 'ignored_test.dart' as ignored_test; 5 | import 'json_diff_test.dart' as json_diff_test; 6 | 7 | void main() { 8 | group('atomics', atomics_test.main); 9 | group('ignored', ignored_test.main); 10 | group('json_diff', json_diff_test.main); 11 | } 12 | --------------------------------------------------------------------------------