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

读取MongoDB格式JSON转Pandas DataFrame遇解码错误求解决

解决MongoDB扩展JSON转Pandas DataFrame的JSONDecodeError问题

你遇到的JSONDecodeError是因为MongoDB导出的JSON包含非标准的自定义类型(比如ObjectId、NumberInt),而Python标准库的json模块只能解析符合RFC规范的标准JSON,所以才会报错。下面给你两种可行的解决方案:

方案一:使用PyMongo的json_util工具(推荐)

PyMongo自带的json_util专门用来处理MongoDB的扩展JSON格式,能自动解析ObjectId、NumberInt这些特殊类型。

步骤:

  1. 先安装PyMongo(如果还没装):
pip install pymongo
  1. 修改你的代码如下:
import pandas as pd
from bson import json_util

path = "NavigatorInstances.json"
with open(path, 'r') as myfile:
    data = myfile.read()

# 用json_util解析MongoDB扩展JSON
parsed_data = json_util.loads(data)

# 转换为Pandas DataFrame
df = pd.json_normalize(parsed_data)

这样处理后,ObjectId会被转换成字符串,NumberInt会转换成Python的整数类型,完美适配Pandas的DataFrame。

方案二:手动替换非标准类型(无需额外安装库)

如果你不想安装PyMongo,可以通过正则表达式把MongoDB的自定义类型语法替换成标准JSON能识别的格式:

import pandas as pd
import json
import re

path = "NavigatorInstances.json"
with open(path, 'r') as myfile:
    data = myfile.read()

# 替换NumberInt(xxx)为纯数字
data = re.sub(r'NumberInt\((\d+)\)', r'\1', data)
# 替换ObjectId("xxx")为字符串"xxx"
data = re.sub(r'ObjectId\("([^"]+)"\)', r'"\1"', data)

# 现在可以用标准json模块解析了
parsed_data = json.loads(data)
df = pd.json_normalize(parsed_data)

这个方法适合快速处理简单的MongoDB JSON文件,但如果你的JSON里还有其他特殊类型(比如ISODate),可能需要补充更多的正则替换规则。

内容的提问来源于stack exchange,提问作者Pavan Suvarna

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 16:32:57