栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用Python将MongoDB的bsondump转换为JSON?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用Python将MongoDB的bsondump转换为JSON?

您所拥有的是TenGen模式下的Mongo Extended
JSON中的转储(请参阅此处)。一些可行的方法:

  1. 如果可以再次转储,请通过MongoDB REST API使用严格输出模式。那应该给您真正的JSON,而不是现在的JSON。

  2. 使用

    bson
    从http://pypi.python.org/pypi/bson/读你已经有了BSON到Python的数据结构,然后做任何处理,你需要对这些(可能输出JSON)。

  3. 使用MongoDB Python绑定连接到数据库以将数据导入Python,然后进行所需的任何处理。(如果需要,您可以设置本地MongoDB实例,然后将转储的文件导入该实例。)

  4. 将Mongo Extended JSON从TenGen模式转换为Strict模式。您可以开发一个单独的过滤器来做到这一点(从stdin读取,将TenGen结构替换为Strict结构,并在stdout上输出结果),也可以在处理输入时做到这一点。

这是一个使用Python和正则表达式的示例:

import json, refrom bson import json_utilwith open("data.tengenjson", "rb") as f:    # read the entire input; in a real application,    # you would want to read a chunk at a time    bsondata = f.read()    # convert the TenGen JSON to Strict JSON    # here, I just convert the ObjectId and Date structures,    # but it's easy to extend to cover all structures listed at    # http://www.mongodb.org/display/DOCS/Mongo+Extended+JSON    jsondata = re.sub(r'ObjectIds*(s*"(S+)"s*)',r'{"$oid": "1"}',bsondata)    jsondata = re.sub(r'Dates*(s*(S+)s*)',r'{"$date": 1}',jsondata)    # now we can parse this as JSON, and use MongoDB's object_hook    # function to get rich Python data structures inside a dictionary    data = json.loads(jsondata, object_hook=json_util.object_hook)    # just print the output for demonstration, along with the type    print(data)    print(type(data))    # serialise to JSON and print    print(json_util.dumps(data))

根据您的目标,其中一个应该是一个合理的起点。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/427629.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号