如何用Python更新多对象JSON文件中的指定last_ping值?
使用Python更新JSON文件中指定对象的last_ping值
要更新JSON文件中某个对象的last_ping值,核心流程是读取JSON数据→定位目标对象→更新字段→写回文件。下面是具体实现步骤(以id作为唯一标识定位对象为例,比name更可靠):
1. 读取JSON文件
用Python内置的json模块将文件内容加载到内存:
import json from datetime import datetime # 替换为你的JSON文件路径 file_path = "your_data.json" with open(file_path, 'r', encoding='utf-8') as f: data = json.load(f)
2. 定位并更新目标对象
遍历data['data']列表,找到匹配对象后同步更新last_ping和last_ping_timestamp(保持两个字段数据一致):
# 要更新的目标对象ID target_id = "4b9b05df-c9d7-4ed6-bde7-d4663414996b" # 生成符合原格式的时间数据 current_time = datetime.now() new_last_ping = current_time.strftime("%Y-%m-%d %H:%M:%S.%f") new_timestamp = int(current_time.timestamp()) # 遍历查找并更新 for item in data['data']: if item['id'] == target_id: item['last_ping'] = new_last_ping item['last_ping_timestamp'] = new_timestamp break # 找到目标后退出循环,提升效率
如果需要通过name定位(注意可能存在重名),只需将判断条件改为item['name'] == "John"即可。
3. 将更新后的数据写回文件
把修改后的内容覆盖写回原文件(操作前建议备份原文件):
with open(file_path, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=4)
注意事项
- 对于数百个对象的文件,直接加载到内存完全可行;如果是超大型JSON文件,可考虑逐行解析优化内存占用。
- 确保
last_ping的格式与原数据一致(原格式为YYYY-MM-DD HH:MM:SS.ffffff),上述代码已匹配该格式。
内容的提问来源于stack exchange,提问作者EZDJSkdjs
相关产品推荐
相关产品推荐

