您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

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

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

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

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

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

import json, re
from bson import json_util

with 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'ObjectId\s*\(\s*\"(\S+)\"\s*\)',
                      r'{"$oid": "\1"}',
                      bsondata)
    jsondata = re.sub(r'Date\s*\(\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))

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

python 2022/1/1 18:14:05 有578人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶