【问题标题】:How to convert a string to BSON?如何将字符串转换为 BSON?
【发布时间】:2015-05-08 00:57:15
【问题描述】:

我有一个这样的字符串:

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 集合时,我收到以下错误:

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

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

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

【问题讨论】:

    标签: python json mongodb pymongo


    【解决方案1】:

    这里重要的不是 BSON 部分。 MongoDB 驱动程序会处理这个问题。您的工作是将 JSON 转换为有效的 Python 数据结构:

    import json
    
    data = json.loads(document)
    
    collection.insert(data);
    

    【讨论】:

    • 猜我想多了。谢谢!
    • @user2215331 我认为一般来说人们会“太着迷”认为 MongoDB 语法是 JSON 只是因为这是给出的示例并且这就是提供的“shell”。 JSON 只是一种以序列化形式表示数据结构的方式。 BSON 的翻译大致相同,只是它具有“类型”定义的概念,这在“强类型”语言中通常是必需的。正如我所说,这里的重点是在必要时使用您的“本机”语言方法来描述数据结构。转换的工作取决于司机。
    • 无论如何,要转换为 bson:import bson; bsondoc = bson.BSON.encode(yourdict_or_json)api.mongodb.com/python/current/api/bson/index.html#bson.BSON
    • @EduardoPignatelli 很清楚这一点。但这不是被问到的问题,即使 “你自己的搜索” 不知何故将你引向了这个问题。问题本身显示(如已回答)关于如何使用 JSON 字符串误解 - “当我尝试将其插入 mongoDB 集合时” i> - 实际上并没有真正询问 BSON。 yourdict_or_json 也不是真的。您可以dict 直接转换为 BSON。如果您有 JSON,那么您同样需要按照答案所示进行转换。请参阅您引用的同一页面下方的encode
    • @NeilLunn 感谢您的更正。我仍然认为这个问题聚集了很多人问实际的标题问题“如何将字符串转换为 BSON?”。所以要更正答案:import bson, json; bsondoc = bson.BSON.encode(json.loads(your_json_string))
    【解决方案2】:

    您很少需要自己直接处理 BSON。这只是 mongo 用来在内部表示数据的格式。

    作为数据库的用户或其客户之一,您只需要处理我们所说的作为文档的key:value 类型的对象。在python中,key:valuelike对象最常见的是dict对象;一本字典。 在将它插入 mongo 之前,您需要将该字符串转换为实际的类似 dict 的对象。

    其中一个例子是使用json 模块:

    >>> import json
    >>> document = json.loads('{ time : 14/09/19 16:00:00...')
    

    您现在可以将document 对象插入您的集合中。

    【讨论】:

      猜你喜欢
      • 2020-03-02
      • 2021-11-26
      • 2017-01-07
      • 1970-01-01
      • 1970-01-01
      • 2019-03-13
      • 1970-01-01
      • 2021-12-28
      • 2012-02-05
      相关资源
      最近更新 更多