英文:
Python's json.dumps function failing to indent
问题
以下是您的代码部分的翻译:
def loadDatabase():
try:
client.admin.command('ping')
#logger.info("成功连接到MongoDB")
#print("数据库 - 您成功连接到MongoDB!")
#flightCollection.delete_many({})
#flightCollection.insert_many(loadFlights())
data = flightCollection.find({})
output = json.dumps(str(data), indent=4)
return output
except Exception as e:
#print(e)
#logger.setLevel(logging.ERROR)
#logger.error(e)
#logger.setLevel(logging.INFO)
return "数据库错误:<br>" + str(e)
def loadFlights():
response = amadeus.shopping.flight_offers_search.get(
originLocationCode='MAD',
destinationLocationCode='ATH',
departureDate=str(date.today()),
adults=1)
return response.data
希望这对您有所帮助。如果您有其他问题,请随时提出。
英文:
I then have a function, loadDatabase, which fully updates a database and then returns it as a JSON (to later be printed to the screen)
The problem is that it prints it in a format that isn't very readable, which normally would be an easy fix with the json.dumps() or bson.json_util.dumps() functions, which can accept an indent parameter. However, I've tried both and neither seem to have any effect.
My relevant code, I've commented out the lines I believe aren't important for this:
def loadDatabase():
try:
client.admin.command('ping')
#logger.info("Successfully connected to MongoDB")
#print("Database - You successfully connected to MongoDB!")
#flightCollection.delete_many({})
#flightCollection.insert_many(loadFlights())
data = flightCollection.find({})
output = json.dumps(str(data), indent=4)
return output
except Exception as e:
#print(e)
#logger.setLevel(logging.ERROR)
#logger.error(e)
#logger.setLevel(logging.INFO)
return "DATABASE ERROR: <br>"+str(e)
def loadFlights():
response = amadeus.shopping.flight_offers_search.get(
originLocationCode='MAD',
destinationLocationCode='ATH',
departureDate=str(date.today()),
adults=1)
return response.data
What can I do to fix this? I've tried both dump functions, but beyond manually writing a function to parse it (which is doable but I don't think I should reinvent the wheel) I don't know what to do
I expected the output to be a formatted JSON, but instead it's all clumped together, eg.:
"{'_id': ObjectId('6481bb02cbb598c58691b45e'), 'type': 'flight-offer', 'id': '2', 'source': 'GDS', 'instantTicketingRequired': False, 'nonHomogeneous': False, 'oneWay': False, 'lastTicketingDate': '2023-06-08', 'lastTicketingDateTime': '2023-06-08', 'numberOfBookableSeats': 3, 'itineraries': [{'duration': 'PT12H5M', 'segments': [{'departure': {'iataCode': 'MAD', 'terminal': '4S', 'at': '2023-06-08T22:10:00'}, 'arrival': {'iataCode': 'TLV', 'terminal': '3', 'at': '2023-06-09T03:45:00'}, 'carrierCode': 'IZ', 'number': '232', 'aircraft': {'code': '73H'}, 'operating': {'carrierCode': 'QS'}, 'duration': 'PT4H35M', 'id': '3', 'numberOfStops': 0, 'blacklistedInEU': False}, {'departure': {'iataCode': 'TLV', 'terminal': '1', 'at': '2023-06-09T09:05:00'}, 'arrival': {'iataCode': 'ATH', 'at': '2023-06-09T11:15:00'}, 'carrierCode': 'IZ', 'number': '211', 'aircraft': {'code': '73H'}, 'operating': {'carrierCode': 'QS'}, 'duration': 'PT2H10M', 'id': '4', 'numberOfStops': 0, 'blacklistedInEU': False}]}], 'price': {'currency': 'EUR', 'total': '147.32', 'base': '112.00', 'fees': [{'amount': '0.00', 'type': 'SUPPLIER'}, {'amount': '0.00', 'type': 'TICKETING'}], 'grandTotal': '147.32', 'additionalServices': [{'amount': '37.33', 'type': 'CHECKED_BAGS'}]}, 'pricingOptions': {'fareType': ['PUBLISHED'], 'includedCheckedBagsOnly': False}, 'validatingAirlineCodes': ['IZ'], 'travelerPricings': [{'travelerId': '1', 'fareOption': 'STANDARD', 'travelerType': 'ADULT', 'price': {'currency': 'EUR', 'total': '147.32', 'base': '112.00'}, 'fareDetailsBySegment': [{'segmentId': '3', 'cabin': 'ECONOMY', 'fareBasis': 'XSIP', 'class': 'X', 'includedCheckedBags': {'quantity': 0}}, {'segmentId': '4', 'cabin': 'ECONOMY', 'fareBasis': 'XSIP', 'class': 'X', 'includedCheckedBags': {'quantity': 0}}]}]}"
I've tried both json.dumps() or bson.json_util.dumps() functions, with a variety of indentations, applied at a variety of different ways, as well as casting to string, list, and several other modifications and variations
答案1
得分: 1
你的代码问题在于你将从MongoDB检索到的数据转换为字符串,然后尝试在该字符串上使用 json.dumps()
。这不会按照你的期望工作,因为 json.dumps()
预期一个字典、列表或其他可JSON序列化的对象,而不是一个字符串。
from bson.json_util import dumps
def loadDatabase():
try:
client.admin.command('ping')
# logger.info("Successfully connected to MongoDB")
# print("Database - You successfully connected to MongoDB!")
# flightCollection.delete_many({})
# flightCollection.insert_many(loadFlights())
data = flightCollection.find({})
# 将游标转换为字典列表
documents = [doc for doc in data]
# 使用 bson.json_util.dumps 来序列化 ObjectId 实例
output = dumps(documents, indent=4)
return output
请注意,我使用了 bson.json_util
中的 dumps
,而不是 json.dumps
,因为它能够序列化在MongoDB中常用作文档ID的 ObjectId
实例。标准的 json.dumps
函数不知道如何序列化这些实例。
更多信息请参阅这里。
英文:
The problem with your code is that you are converting the data retrieved from MongoDB into a string, and then trying to use json.dumps()
on that string. This will not work as you expect, since json.dumps()
expects a dictionary, list, or other JSON serializable object, not a string.
from bson.json_util import dumps
def loadDatabase():
try:
client.admin.command('ping')
# logger.info("Successfully connected to MongoDB")
# print("Database - You successfully connected to MongoDB!")
# flightCollection.delete_many({})
# flightCollection.insert_many(loadFlights())
data = flightCollection.find({})
# Convert cursor into list of dictionaries
documents = [doc for doc in data]
# Use bson.json_util.dumps to serialize the ObjectId's
output = dumps(documents, indent=4)
return output
Notice that I used dumps from bson.json_util
instead of json.dumps
because it is capable of serializing ObjectId
instances that are commonly used as document IDs in MongoDB. The standard json.dumps
function does not understand how to serialize these instances.
Read more here
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论