I have data and i want to create method to compare this data with JSON data from an API anyone know how to do this ?
2 Answers
Someone from google seems to have had a shot at it, maybe try: https://github.com/google/dart-json_diff
1 Comment
Thomas Weller
As it is, this is a link-only answer. Please consider adding the most important information from the linked reference.
Hope my answer helps you .. upvote if you like
Below is the method you can use for comparing the two json in dart
bool compareJson(dynamic json1, dynamic json2) {
// Check if the types of the objects are the same
if (json1.runtimeType != json2.runtimeType) {
return false;
}
// Compare dictionaries
if (json1 is Map<String, dynamic> && json2 is Map<String, dynamic>) {
// Check if both dictionaries have the same keys
if (!json1.keys.toSet().containsAll(json2.keys.toSet()) ||
!json2.keys.toSet().containsAll(json1.keys.toSet())) {
return false;
}
// Recursively compare the values for each key
for (var key in json1.keys) {
if (!compareJson(json1[key], json2[key])) {
return false;
}
}
return true;
}
// Compare lists
if (json1 is List<dynamic> && json2 is List<dynamic>) {
// Check if both lists have the same length
if (json1.length != json2.length) {
return false;
}
// Recursively compare the values at each index
for (var i = 0; i < json1.length; i++) {
if (!compareJson(json1[i], json2[i])) {
return false;
}
}
return true;
}
// Compare other types of values
return json1 == json2;
}
example
void main() {
// Example JSON objects
var json1 = {
"name": "John",
"address": {
"street": "123 Main St",
"city": "New York"
},
"age": 30,
};
var json2 = {
"name": "John",
"age": 30,
"address": {
"street": "123 Main St",
"city": "New York"
}
};
// Compare the JSON objects
var result = compareJson(json1, json2);
// Check the result
if (result) {
print("The JSON objects are identical.");
} else {
print("The JSON objects are not identical.");
}
}