Python的json.dumps函数无法正确缩进。

huangapple go评论79阅读模式
英文:

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(&#39;ping&#39;)
        #logger.info(&quot;Successfully connected to MongoDB&quot;)
        #print(&quot;Database - You successfully connected to MongoDB!&quot;)
        #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 &quot;DATABASE ERROR: &lt;br&gt;&quot;+str(e)

def loadFlights(): 
    response = amadeus.shopping.flight_offers_search.get(
        originLocationCode=&#39;MAD&#39;,
        destinationLocationCode=&#39;ATH&#39;,
        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.:

&quot;{&#39;_id&#39;: ObjectId(&#39;6481bb02cbb598c58691b45e&#39;), &#39;type&#39;: &#39;flight-offer&#39;, &#39;id&#39;: &#39;2&#39;, &#39;source&#39;: &#39;GDS&#39;, &#39;instantTicketingRequired&#39;: False, &#39;nonHomogeneous&#39;: False, &#39;oneWay&#39;: False, &#39;lastTicketingDate&#39;: &#39;2023-06-08&#39;, &#39;lastTicketingDateTime&#39;: &#39;2023-06-08&#39;, &#39;numberOfBookableSeats&#39;: 3, &#39;itineraries&#39;: [{&#39;duration&#39;: &#39;PT12H5M&#39;, &#39;segments&#39;: [{&#39;departure&#39;: {&#39;iataCode&#39;: &#39;MAD&#39;, &#39;terminal&#39;: &#39;4S&#39;, &#39;at&#39;: &#39;2023-06-08T22:10:00&#39;}, &#39;arrival&#39;: {&#39;iataCode&#39;: &#39;TLV&#39;, &#39;terminal&#39;: &#39;3&#39;, &#39;at&#39;: &#39;2023-06-09T03:45:00&#39;}, &#39;carrierCode&#39;: &#39;IZ&#39;, &#39;number&#39;: &#39;232&#39;, &#39;aircraft&#39;: {&#39;code&#39;: &#39;73H&#39;}, &#39;operating&#39;: {&#39;carrierCode&#39;: &#39;QS&#39;}, &#39;duration&#39;: &#39;PT4H35M&#39;, &#39;id&#39;: &#39;3&#39;, &#39;numberOfStops&#39;: 0, &#39;blacklistedInEU&#39;: False}, {&#39;departure&#39;: {&#39;iataCode&#39;: &#39;TLV&#39;, &#39;terminal&#39;: &#39;1&#39;, &#39;at&#39;: &#39;2023-06-09T09:05:00&#39;}, &#39;arrival&#39;: {&#39;iataCode&#39;: &#39;ATH&#39;, &#39;at&#39;: &#39;2023-06-09T11:15:00&#39;}, &#39;carrierCode&#39;: &#39;IZ&#39;, &#39;number&#39;: &#39;211&#39;, &#39;aircraft&#39;: {&#39;code&#39;: &#39;73H&#39;}, &#39;operating&#39;: {&#39;carrierCode&#39;: &#39;QS&#39;}, &#39;duration&#39;: &#39;PT2H10M&#39;, &#39;id&#39;: &#39;4&#39;, &#39;numberOfStops&#39;: 0, &#39;blacklistedInEU&#39;: False}]}], &#39;price&#39;: {&#39;currency&#39;: &#39;EUR&#39;, &#39;total&#39;: &#39;147.32&#39;, &#39;base&#39;: &#39;112.00&#39;, &#39;fees&#39;: [{&#39;amount&#39;: &#39;0.00&#39;, &#39;type&#39;: &#39;SUPPLIER&#39;}, {&#39;amount&#39;: &#39;0.00&#39;, &#39;type&#39;: &#39;TICKETING&#39;}], &#39;grandTotal&#39;: &#39;147.32&#39;, &#39;additionalServices&#39;: [{&#39;amount&#39;: &#39;37.33&#39;, &#39;type&#39;: &#39;CHECKED_BAGS&#39;}]}, &#39;pricingOptions&#39;: {&#39;fareType&#39;: [&#39;PUBLISHED&#39;], &#39;includedCheckedBagsOnly&#39;: False}, &#39;validatingAirlineCodes&#39;: [&#39;IZ&#39;], &#39;travelerPricings&#39;: [{&#39;travelerId&#39;: &#39;1&#39;, &#39;fareOption&#39;: &#39;STANDARD&#39;, &#39;travelerType&#39;: &#39;ADULT&#39;, &#39;price&#39;: {&#39;currency&#39;: &#39;EUR&#39;, &#39;total&#39;: &#39;147.32&#39;, &#39;base&#39;: &#39;112.00&#39;}, &#39;fareDetailsBySegment&#39;: [{&#39;segmentId&#39;: &#39;3&#39;, &#39;cabin&#39;: &#39;ECONOMY&#39;, &#39;fareBasis&#39;: &#39;XSIP&#39;, &#39;class&#39;: &#39;X&#39;, &#39;includedCheckedBags&#39;: {&#39;quantity&#39;: 0}}, {&#39;segmentId&#39;: &#39;4&#39;, &#39;cabin&#39;: &#39;ECONOMY&#39;, &#39;fareBasis&#39;: &#39;XSIP&#39;, &#39;class&#39;: &#39;X&#39;, &#39;includedCheckedBags&#39;: {&#39;quantity&#39;: 0}}]}]}&quot;

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(&#39;ping&#39;)
        # logger.info(&quot;Successfully connected to MongoDB&quot;)
        # print(&quot;Database - You successfully connected to MongoDB!&quot;)
        # 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&#39;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

huangapple
  • 本文由 发表于 2023年6月8日 19:27:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76431385.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定