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

导入JSON至MongoDB时遭遇JSONDecodeError与StopIteration错误求助

问题:JSON导入MongoDB时触发JSONDecodeError错误

尝试将JSON文件导入MongoDB,使用官方文档的Python代码时,在myDict = json.loads(jsonObj)语句处出现以下错误:

obj, end = self.scan_once(s, idx)

builtins.StopIteration: 2

During handling of the above exception, another exception occurred:

File "/Users/s/Documents/s/importToMongo.py", line 13, in <module>
  myDict = json.loads(jsonObj)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/__init__.py", line 346, in loads
  return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/decoder.py", line 337, in decode
  obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/decoder.py", line 355, in raw_decode
  raise JSONDecodeError("Expecting value", s, err.value) from None

json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 2)

已通过在线工具验证JSON内容有效,JSON内容如下:

[
    {
        "field1": "6405441",
        "field9": "326",
        "field10": "12",
        "field17": "1180",
        "field22": "Avenue Brugmann",
        "field23": "Brugmannlaan",
        "field24": null,
        "field28": "Uccle",
        "field29": "Ukkel",
        "field30": null,
        "field13": "648301.355 666355.729"
    },
    {
        "field1": "fid",
        "field9": "housenumber",
        "field10": "boxnumber",
        "field17": "postal_info_objectid",
        "field22": "streetname_fr",
        "field23": "streetname_nl",
        "field24": "streetname_de",
        "field28": "municipality_fr",
        "field29": "municipality_nl",
        "field30": "municipality_de",
        "field13": "position"
    }
]

解决办法

1. 改用json.load()直接读取文件对象

不要先把文件内容读成字符串再用json.loads(),直接用json.load()读取打开的文件对象,避免读取过程中出现的格式问题:

import json
from pymongo import MongoClient

# 连接MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client['your_database_name']
collection = db['your_collection_name']

# 正确读取并解析JSON文件
with open('your_json_file.json', 'r', encoding='utf-8') as f:
    json_data = json.load(f)

# 批量插入数据到MongoDB
collection.insert_many(json_data)

2. 检查文件编码(处理UTF-8 BOM)

如果JSON文件保存时带有UTF-8 BOM,会导致解析失败,改用utf-8-sig编码读取:

with open('your_json_file.json', 'r', encoding='utf-8-sig') as f:
    json_data = json.load(f)

3. 确认文件读取方式正确

如果你之前是逐行读取文件(比如用readline()或循环读取),会导致jsonObj只包含部分内容,触发解析错误。必须一次性读取整个文件内容:

# 错误示例:逐行读取会导致内容不完整
with open('file.json', 'r') as f:
    jsonObj = f.readline()  # 只读取了第一行,导致JSON不完整

# 正确示例:一次性读取全部内容
with open('file.json', 'r') as f:
    jsonObj = f.read()
    json_data = json.loads(jsonObj)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 10:55:21