在尝试将insert_one插入集合之后。我收到此错误:
bson.errors.InvalidDocument: cannot encode object: Decimal('0.16020'), of type: <class 'decimal.Decimal'>
当 JSON 不包含decimal.Decimal对象时,代码运行良好。如果有解决方案,您能否考虑以递归方式对其进行编码,以使整个 python 字典json_dic兼容以插入到 MongoDB 中(因为条目中有不止一次的类 decimal.Decimal 实例json.dic)。
编辑 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,希望能找出问题所在(也作为屏幕截图):
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
}
'
www说
胡说叔叔
收到一只叮咚
BIG阳
慕无忌1623718
随时随地看视频慕课网APP
相关分类