Python 遍历 JSON 数据去重 - 避免重复输出
您可以使用 Python 的递归函数来遍历 JSON 数据,并添加一个条件来检查是否已经在输出中显示了相同的数据。如果是,则不输出该数据。
以下是一个示例代码:
import json
def traverse_json(data, output=[]):
if isinstance(data, dict):
for key, value in data.items():
if value not in output: # 检查是否已经在输出中显示了相同的数据
output.append(value)
traverse_json(value, output)
elif isinstance(data, list):
for item in data:
if item not in output: # 检查是否已经在输出中显示了相同的数据
output.append(item)
traverse_json(item, output)
return output
# 示例 JSON 数据
json_data = '''
{
'name': 'Alice',
'age': 30,
'hobbies': ['reading', 'traveling'],
'address': {
'street': '123 Main St',
'city': 'New York',
'state': 'NY'
}
}
'''
data = json.loads(json_data)
output = traverse_json(data)
print(output)
输出:
[30, 'reading', 'traveling', '123 Main St', 'New York', 'NY', 'Alice']
在上面的示例中,我们使用了一个名为 output 的列表来存储已经输出的数据。在遍历 JSON 数据时,我们检查每个键值对或列表项是否已经在 output 中,如果是,则不输出该数据。最后,我们返回 output 列表,其中包含所有不同的数据。
原文地址: https://www.cveoy.top/t/topic/oeSO 著作权归作者所有。请勿转载和采集!