You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python提取Facebook消息JSON指定字段正序导出及KeyError问题解决

代码修复方案

错误原因说明

  • 触发KeyError: 'message'的核心原因:JSON根节点下存储消息列表的键名为复数messages,你的代码中错误写成了单数message
  • 其余隐藏问题:
    • timestamp_ms是毫秒级时间戳,datetime.fromtimestamp()仅支持秒级时间戳,需要除以1000转换单位
    • datetime时间对象无法直接和字符串拼接,需要调用格式化方法转为字符串
    • 换行符语法错误,应为\r\n而非/r/n
    • 倒序写入时取长度的对象错误,应该取dataarray的长度而非原始JSON数据data的长度,否则会出现索引越界
    • 部分特殊消息(撤回消息、附件/图片消息)不存在content字段,建议增加字段存在性判断避免二次报错
    • 缺少编码声明,处理中文内容时容易出现乱码

修复后完整代码

import json
import datetime

# 增加utf-8编码声明避免乱码
with open("message_1.json", encoding="utf-8") as file:
    data = json.load(file)

dataarray = []

# 遍历消息列表,键名修改为复数messages
for doc in data['messages']:
    # 毫秒转秒,转换为时间对象后格式化输出
    epochdatetime = datetime.datetime.fromtimestamp(doc['timestamp_ms'] / 1000)
    time_str = epochdatetime.strftime("%Y-%m-%d %H:%M:%S")
    # 兼容无content的特殊消息
    content = doc.get('content', '[无文本内容/特殊消息]')
    linetowrite = f"{time_str} {doc['sender_name']}: {content}\r\n"
    dataarray.append(linetowrite)

# 用with语法自动管理文件关闭,倒序写入实现时间正序排列
with open('messages.txt', 'w', encoding="utf-8") as openfile:
    for line in reversed(dataarray):
        openfile.write(line)

内容的提问来源于stack exchange,提问作者Anthro Teacher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 10:00:01