1

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 2

2

Someone from google seems to have had a shot at it, maybe try: https://github.com/google/dart-json_diff

Sign up to request clarification or add additional context in comments.

1 Comment

As it is, this is a link-only answer. Please consider adding the most important information from the linked reference.
1

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.");
      }
}
  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.