remove duplicates in json in flutter
To remove duplicates in a JSON array in Flutter, you can follow these steps:
- Parse the JSON string into a list of objects using the
json.decode()
method. - Convert the list into a
Set
to remove duplicates. - Convert the
Set
back into a list using thetoList()
method. - Encode the list back into a JSON string using the
json.encode()
method.
Here's an example code snippet that demonstrates this process:
import 'dart:convert';
void main() {
String jsonString = '[{"id": 1, "name": "John"}, {"id": 2, "name": "Jane"}, {"id": 1, "name": "John"}]';
List<dynamic> jsonList = json.decode(jsonString);
List<dynamic> uniqueList = jsonList.toSet().toList();
String uniqueJsonString = json.encode(uniqueList);
print(uniqueJsonString);
}
In this example, the jsonString
variable represents the JSON string with duplicates. The json.decode()
method is used to parse the JSON string into a list of objects. The toSet()
method is then used to convert the list into a Set
, which automatically removes duplicates. Finally, the toList()
method converts the Set
back into a list, and the json.encode()
method is used to encode the list back into a JSON string.
When you run this code, the output will be:
[{"id":1,"name":"John"},{"id":2,"name":"Jane"}]
This is the JSON string with duplicates removed.