Преобразование BSON в JSON в Python

Чтобы преобразовать BSON в JSON в Python, вы можете использовать разные методы в зависимости от имеющихся у вас библиотек. Вот несколько способов:

Метод 1: модули bson и json

import bson
import json
# Read BSON data from a file or a variable
with open('data.bson', 'rb') as file:
    bson_data = file.read()
# Convert BSON to JSON
json_data = json.dumps(bson.loads(bson_data))
# Print or save the JSON data
print(json_data)

Метод 2: модуль pymongo

from pymongo import MongoClient
import json
# Connect to MongoDB
client = MongoClient('mongodb://localhost:27017')
# Access your collection
db = client['your_database']
collection = db['your_collection']
# Retrieve BSON data from the collection
bson_data = collection.find_one()
# Convert BSON to JSON
json_data = json.dumps(bson_data, default=str)
# Print or save the JSON data
print(json_data)

Метод 3: модуль bsonjson

import bsonjson
import json
# Read BSON data from a file or a variable
with open('data.bson', 'rb') as file:
    bson_data = file.read()
# Convert BSON to JSON
json_data = json.dumps(bsonjson.loads(bson_data))
# Print or save the JSON data
print(json_data)