Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dart

The following code prints:

false
false
true
{{a: b}, {a: b}}

code

import "dart:json" as JSON;

main() {
  print(JSON.parse('{ "a" : "b" }') == JSON.parse('{ "a" : "b" }'));
  print({ "a" : "b" } == { "a" : "b" });
  print({ "a" : "b" }.toString() == { "a" : "b" }.toString());
  Set s = new Set();
  s.add(JSON.parse('{ "a" : "b" }'));
  s.add(JSON.parse('{ "a" : "b" }'));
  print(s);
}

I am using json and parsing two equivalent objects, storing them in a Set, hoping they will not be duplicated. This is not the case and it seems to be because the first two lines (unexpectedly?) results in false. What is an efficient way to correctly compare two Map objects assuming each were the result of JSON.parse()?

like image 698
user1338952 Avatar asked Aug 19 '13 20:08

user1338952


1 Answers

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?.

like image 55
Patrice Chalin Avatar answered Oct 25 '22 14:10

Patrice Chalin