可以使用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数据只输出了一份

怎么把Python里面相同的JSON输出相同的只输出一份

原文地址: https://www.cveoy.top/t/topic/fp1q 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录