【发布时间】:2020-08-10 21:13:26
【问题描述】:
尝试将insert_one 放入集合后。 我收到此错误:
bson.errors.InvalidDocument: cannot encode object: Decimal('0.16020'), of type: <class 'decimal.Decimal'>
当 JSON 不包含 decimal.Decimal 对象时,代码运行良好。如果有解决方案,您是否可以考虑以递归方式对其进行编码,以使整个 python 字典 json_dic 兼容以插入到 MongoDB 中(因为在 @987654327 中有不止一次的类 decimal.Decimal 的实例@条目)。
任何帮助将不胜感激!
编辑 1:这是我正在处理的 json
import simplejson as json
from pymongo import MongoClient
json_string = '{"A" : {"B" : [{"C" : {"Horz" : 0.181665435,"Vert" : 0.178799435}}]}}'
json_dict = json.loads(json_string)
this_collection.insert_one(json_dict)
这会产生
bson.errors.InvalidDocument: cannot encode object: Decimal('0.181665435'), of type: <class 'decimal.Decimal'>
编辑 2: 不幸的是,我上面的示例过于简化了我现有的 JSON,@Belly Buster 提供的答案(尽管上面的 Json 可以正常工作)出现错误:
AttributeError: 'decimal.Decimal' object has no attribute 'items'
使用我的实际 Json,所以我在这里提供完整的 Json,希望能找出问题所在(也是 as a screen-shot):
json_string =
'
{
"Setting" : {
"GridOptions" : {
"Student" : "HighSchool",
"Lesson" : 1,
"Attended" : true
},
"Grades" : [
80,
50.75
],
"Count" : 2,
"Check" : "Coursework",
"Passed" : true
},
"Slides" : [
{
"Type" : "ABC",
"Duration" : 1.5
},
{
"Type" : "DEF",
"Duration" : 0.5
}
],
"Work" : {
"Class" : [
{
"Time" : 123456789,
"Marks" : {
"A" : 50,
"B" : 100
}
}
],
"CourseWorkDetail" : [
{
"Test" : {
"Mark" : 0.987654321
},
"ReadingDate" : "Feb162006",
"Reading" : 300.001,
"Values" : [
[
0.98765
],
[
-0.98765
]
]
},
{
"Test" : {
"Mark" : 0.123456789
},
"ReadingDate" : "Jan052010",
"Reading" : 200.005,
"Values" : [
[
0.12345
],
[
-0.12345
]
]
}
]
},
"listing" : 5
}
'
编辑 3: 作为对下面答案的补充,您可以像这样在字典中递归迭代并使用答案中的函数
def iterdict(dict_items, debug_out):
for k, v in dict_items.items():
if isinstance(v):
iterdict(v)
else:
dict_items[k] = convert_decimal(v)
return dict_items
【问题讨论】:
-
请使用您尝试过的代码更新您的帖子。
-
我已经添加了代码
-
您添加的代码在 mongo 4.2 版上运行没有错误。你运行的是什么版本?您是否运行了确切的代码(没有看到任何连接线)?
标签: python json mongodb decimal pymongo