如何将字符串转换为BSON? [英] How to convert a string to BSON?

查看:707
本文介绍了如何将字符串转换为BSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的字符串:

I have a string like this:

document = '{ time : 14/09/19 16:00:00,
   global : { full:190 , defects: 7 , btp: 6 , total: 202 } ,
   domains : [ { domain : "A" , full:7 , defects: 2 , btp: 0 , total: 9 },
               { domain : "B" , full:0 , defects: 0 , btp: 0 , total: 0 },
               { domain : "C" , full:6 , defects: 0 , btp: 0 , total: 6 },
               { domain : "D" , full:26 , defects: 0 , btp: 2 , total: 28 },
               { domain : "E" , full:0 , defects: 0 , btp: 0 , total: 0 },
               { domain : "F" , full:4 , defects: 0 , btp: 2 , total: 6 },
               { domain : "G" , full:0 , defects: 0 , btp: 0 , total: 0 },
               { domain : "H" , full:21 , defects: 0 , btp: 1 , total: 22 },
               { domain : "I" , full:32 , defects: 0 , btp: 0 , total: 32 },
               ] }'

当我尝试将其插入mongoDB集合时,出现以下错误:

When I try to insert this into a mongoDB collection, I get the following error:

TypeError:'str'对象不支持项目分配

TypeError: 'str' object does not support item assignment

对于如何将字符串转换为BSON以便执行插入操作,我一无所知.

I am clueless about how to convert a string to BSON, in order to execute the insert with it.

我查看了bson_util模块,但是没有运气.

I looked in the bson_util module, but no luck.

推荐答案

在这里,重要的不是BSON部分. MongoDB驱动程序将解决此问题.您的工作是将JSON转换为有效的python数据结构:

It's not the BSON part that matters here. The MongoDB driver will take care of that. Your job is convert JSON to a valid python data structure:

import json

data = json.loads(document)

collection.insert(data);

这篇关于如何将字符串转换为BSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆