what is a good way to test parsed json maps for equality?

The recommended way to compare JSON maps or lists, possibly nested, for equality is by using the Equality classes from the following package

import 'package:collection/collection.dart';

E.g.,

Function eq = const DeepCollectionEquality().equals;
var json1 = JSON.parse('{ "a" : 1, "b" : 2 }');
var json2 = JSON.parse('{ "b" : 2, "a" : 1 }');
print(eq(json1, json2)); // => true

For details see this answer which talks about some of the different equality classes: How can I compare Lists for equality in Dart?.


This is a difficult one, because JSON objects are just Lists and Maps of num, String, bool and Null. Testing Maps and Lists on equality is still an issue in Dart, see https://code.google.com/p/dart/issues/detail?id=2217

UPDATE

This answer is not valid anymore, see answer @Patrice_Chalin


This is actually pretty hard, as the == operator on Maps and Lists doesn't really compare keys/values/elements to each other.

Depending on your use case, you may have to write a utility method. I once wrote this quick and dirty function:

bool mapsEqual(Map m1, Map m2) {
    Iterable k1 = m1.keys;
    Iterable k2 = m2.keys;
    // Compare m1 to m2
    if(k1.length!=k2.length) return false;
    for(dynamic o in k1) {
        if(!k2.contains(o)) return false;
        if(m1[o] is Map) {
            if(!(m2[o] is Map)) return false;
            if(!mapsEqual(m1[o], m2[o])) return false;
        } else {
            if(m1[o] != m2[o]) return false;
        }
    }
    return true;
}

Please note that while it handles nested JSON objects, it will always return false as soon as nested lists are involved. If you want to use this approach, you may need to add code for handling this.

Another approach I once started was to write wrappers for Map and List (implementing Map/List to use it normally) and override operator==, then use JsonParser and JsonListener to parse JSON strings using those wrappers. As I abandoned that pretty soon, I don't have code for it and don't know if it really would have worked, but it could be worth a try.

Tags:

Dart