Python去重相同JSON数据:集合(Set)方法
Python去重相同JSON数据:集合(Set)方法
可以使用Python的集合(Set)来去重相同的JSON数据。具体的做法是,将每个JSON数据转换成字符串形式,然后将这些字符串放入一个Set中,Set会自动去重,最后将Set中的字符串再转换回JSON格式即可。
下面是一个示例代码:
import json
json_list = [
{'name': 'Tom', 'age': 25},
{'name': 'Jerry', 'age': 30},
{'name': 'Tom', 'age': 25}
]
# 将每个JSON转换成字符串并放入Set中去重
json_set = set(json.dumps(j) for j in json_list)
# 将Set中的字符串再转换回JSON格式输出
json_list_unique = [json.loads(j) for j in json_set]
print(json_list_unique)
输出结果为:
[{'name': 'Jerry', 'age': 30}, {'name': 'Tom', 'age': 25}]
可以看到,相同的JSON数据只输出了一份。
原文地址: https://www.cveoy.top/t/topic/oeSw 著作权归作者所有。请勿转载和采集!