求实现去除任意数据集重复行的通用方法技术方案
Got it, let's figure out how to build a universal method to remove duplicate rows from a JSONArray—no matter what columns or data types the dataset has. Here's a practical, flexible approach that works across different scenarios:
A "duplicate row" means two JSONObject entries have identical key-value pairs (regardless of key order, since JSON objects don't care about key sequence). The plan is:
- Generate a unique, consistent identifier for each JSONObject
- Track which identifiers we've already seen using a set
- Only keep entries whose identifier hasn't been seen before
1. Generate Consistent Identifiers
To avoid false duplicates caused by different key orders, first sort the keys of each JSONObject. Then create a string (or hash) that combines all sorted key-value pairs—this ensures identical objects produce the same identifier, even if their keys are ordered differently.
2. Track Seen Entries
Use a HashSet (or similar set structure) to store identifiers of rows we've already added to the result. This gives O(1) lookups to check for duplicates quickly.
3. Build the Unique Dataset
Loop through each entry in the original JSONArray:
- Generate the identifier for the current JSONObject
- If it's not in the set, add the identifier to the set and the object to the result array
Java (using org.json library)
import org.json.JSONArray; import org.json.JSONObject; import java.util.HashSet; import java.util.Set; public class JsonDuplicateCleaner { public static JSONArray removeDuplicates(JSONArray originalData) { JSONArray uniqueData = new JSONArray(); Set<String> seenIdentifiers = new HashSet<>(); for (int i = 0; i < originalData.length(); i++) { JSONObject currentRow = originalData.getJSONObject(i); String rowId = generateRowIdentifier(currentRow); if (!seenIdentifiers.contains(rowId)) { seenIdentifiers.add(rowId); uniqueData.put(currentRow); } } return uniqueData; } private static String generateRowIdentifier(JSONObject row) { // Sort keys to ensure consistent ordering String[] sortedKeys = row.keySet().toArray(new String[0]); java.util.Arrays.sort(sortedKeys); StringBuilder identifier = new StringBuilder(); for (String key : sortedKeys) { Object value = row.get(key); // Append key-value pairs in sorted order identifier.append(key).append(":").append(value.toString()).append(";"); } // Optionally use a hash for shorter strings (e.g., identifier.toString().hashCode()) return identifier.toString(); } }
Python
import json def remove_duplicate_rows(json_array): seen = set() unique_rows = [] for row in json_array: # Sort the row's items to create a consistent string sorted_row = sorted(row.items()) row_str = json.dumps(sorted_row) if row_str not in seen: seen.add(row_str) unique_rows.append(row) return unique_rows
- Type Strictness: The examples above treat values like
11(Integer) and11.0(Double) as different. If you need to consider them identical, add logic to normalize values (e.g., convert numbers to a common type before generating the identifier). - Hash Collisions: Using a raw string identifier avoids collision risks entirely. If you opt for a hash (like MD5), keep in mind that while collisions are extremely rare, they're technically possible—use this only if memory is a concern.
- Performance: This approach runs in O(n log k) time (where n is the number of rows, k is the average number of columns) due to sorting keys, which is efficient for most real-world datasets.
For your first example dataset, the duplicate row (Id=11, Value=0.1, Person=Arya) will generate the same identifier as its twin. The method will skip adding it to the result, leaving you with only unique rows.
内容的提问来源于stack exchange,提问作者Arnab Bhagabati

