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

Pymongo插入数据后无法序列化返回指定JSON格式问题求助

解决方案

问题核心

InsertManyResult 和 InsertOneResult 是PyMongo的内置对象,包含数据库操作的元数据,但无法直接被json.dumps()序列化,必须手动提取所需字段后构造符合要求的字典。

代码调整方案

1. 重构结果构造逻辑

根据你需要的JSON格式,手动创建包含ok、msg、count的字典:

  • ok:1表示操作成功,0表示失败
  • msg:直接复用插入的原始数据
  • count:通过PyMongo结果对象的inserted_count属性获取实际插入数量

2. 完善异常处理

在初始化、输入解析、插入操作的各个环节都添加异常处理,确保无论成功失败都返回统一格式的结果。

完整调整后的代码

import pymongo
import json

def init_db(ip, db, coll):
    try:
        myclient = pymongo.MongoClient(f'mongodb://{ip}/')
        mydb = myclient[db]
        mycol = mydb[coll]
        return mydb, mycol, True
    except Exception:
        return None, None, False

def ins_data(mycol, one_or_many_bool, insert_values_json):
    # 初始化默认失败结果
    result = {
        "ok": 0,
        "msg": [],
        "count": 0
    }
    try:
        if one_or_many_bool:
            insert_result = mycol.insert_many(insert_values_json)
            result["count"] = insert_result.inserted_count
            result["msg"] = insert_values_json
        else:
            mycol.insert_one(insert_values_json)
            result["count"] = 1
            result["msg"] = [insert_values_json]
        # 操作成功,更新状态
        result["ok"] = 1
        return result
    except Exception:
        # 操作失败,保持默认失败状态
        return result

# 交互输入流程
ip_input = input("Enter the ip: ")
exist_DB_name = input("Enter exist DB name: ")
exist_coll_name = input("Enter exist collection name: ")

mydb, mycol, init_success = init_db(ip_input, exist_DB_name, exist_coll_name)
if not init_success:
    print(json.dumps({"ok":0, "msg":"数据库初始化失败", "count":0}, ensure_ascii=False))
    exit()

insert_one_or_many = input("U are insert one or many values? ( 1 for many, 0 for one ): ")
newvalues_str = input("Enter new values: ")

# 输入格式校验
try:
    one_or_many_bool = bool(int(insert_one_or_many))
    insert_values_json = json.loads(newvalues_str)
except:
    print(json.dumps({"ok":0, "msg":"输入格式错误", "count":0}, ensure_ascii=False))
    exit()

# 执行插入并输出结果
final_result = ins_data(mycol, one_or_many_bool, insert_values_json)
print(json.dumps(final_result, ensure_ascii=False))

关键修改说明

  • 将init_db的返回值改为布尔类型的初始化状态,简化后续流程判断
  • ins_data函数直接返回构造好的结果字典,避免序列化PyMongo内置对象
  • 增加输入格式校验,防止因非法输入导致程序崩溃
  • 成功时自动匹配单/多条数据的格式,确保msg始终为数组类型

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 08:40:25