mongodb 字符串转bson_如何使用Python将MongoDB的bsondump转换为JSON?

小编典典

您所拥有的是TenGen模式下的Mongo Extended

JSON中的转储(请参阅此处)。一些可行的方法:

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

使用bson从http://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))

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

2020-07-27

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值