我正试图从一些使用MongoClient
的线程的MongoDB port
中提取数据。但是,当writing
到JSON
文件时,我遇到了一个错误。我认为传入的data
中有一个Binary
数据类型。如何修复此错误?
我的代码:
import json
import pymongo as pymongo
def get_ip_data():
db_datas = []
for ip_line in json_data:
try:
replace_ip = ip_line.replace("n", "")
client = pymongo.MongoClient(replace_ip, 27017)
client.server_info()
db_names = client.list_database_names()
list_collections = client.admin.command({'listCollections': 1.0}, {'authorizedCollections': True})
host_info = client.admin.command({'hostInfo': 1})
server_status = client.admin.command({'serverStatus': 1})
lock_info = client.admin.command({'lockInfo': 1})
build_info = client.admin.command({'buildInfo': 1})
db_data = {f"{ip_line}, db_names": db_names, "collections_list": list_collections,
"server_status": server_status, "host_info": host_info, "lock_info": lock_info,
"build_info": build_info}
db_datas.append(db_data)
except Exception as e:
print(e)
finally:
with open("./data.json", "wt") as write_data:
write_data.write(json.dumps(db_datas, indent=4))
if __name__ == "__main__":
with open("./ip_list.txt", "r") as json_data:
json_data = json_data.readlines()
get_ip_data()
解决方案取决于您希望在结果中得到什么
推荐的方法是使用pymongo的bson.json_util将带有bson类型对象的字典正确地转储到json。在这种情况下,它们将被表示为类似的东西
"your_binary_field": {
"$binary": {
"base64": "Xi6aRRv9SWAJtTK4ScAoKDrw4cU5bek=",
"subType": "00"
}
},
bson包可以正确读取。
或者,您可以递归地遍历db_datas
项,并强制转换所有bson。二进制对象到字符串,或其他json可序列化值,作为expample,使用bson。二进制代码