以下是一个示例代码,用于按照名称对JSON进行分组,并显示每个组中的最新记录:
import json
from collections import defaultdict
# 示例JSON数据
json_data = '''
[
{"name": "John", "timestamp": "2022-01-01 10:00:00"},
{"name": "Jane", "timestamp": "2022-01-02 12:00:00"},
{"name": "John", "timestamp": "2022-01-03 09:00:00"},
{"name": "Jane", "timestamp": "2022-01-04 15:00:00"},
{"name": "John", "timestamp": "2022-01-05 14:00:00"}
]
'''
# 将JSON数据解析为Python对象
data = json.loads(json_data)
# 使用defaultdict创建一个字典,按名称分组并保存最新记录
grouped_data = defaultdict(dict)
for item in data:
name = item['name']
timestamp = item['timestamp']
if timestamp > grouped_data[name].get('timestamp', ''):
grouped_data[name] = item
# 打印每个组中的最新记录
for name, item in grouped_data.items():
print(f"Name: {name}, Latest Record: {item}")
输出结果:
Name: John, Latest Record: {'name': 'John', 'timestamp': '2022-01-05 14:00:00'}
Name: Jane, Latest Record: {'name': 'Jane', 'timestamp': '2022-01-04 15:00:00'}
该示例中,首先将JSON数据解析为Python对象。然后,使用defaultdict
创建一个字典,它会自动为每个新的名称创建一个空字典。遍历数据列表,对于每个项目,检查其时间戳是否大于当前组中已保存的最新时间戳。如果是,则将该项目保存为当前组的最新记录。最后,打印每个组中的最新记录。