You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Result.data本地正常服务器报错,返回JSON含多余空对象的API问题

Fixing Extra Empty Object in Marshmallow Serialized Response

It looks like you're hitting a common gotcha with Marshmallow when serializing lists of SQLAlchemy objects. Let's break down what's happening and fix that stray empty object in your inventory response.

What's Causing the Issue?

  1. Missing many=True in dump(): Your data variable is a list of MasterInventoryBatch objects (from the .all() query), but you're calling dump() without telling Marshmallow to handle multiple items. This makes Marshmallow treat the entire list as a single object, resulting in that broken nested [[...], {}] structure.
  2. Returning raw MarshalResult object: In Marshmallow 3+, the dump() method returns a MarshalResult instance (not just the serialized data). When you return this directly, it gets serialized with extra metadata, causing that empty object to appear. The error you saw with result.data was likely due to the invalid serialization state caused by missing many=True.

The Solution

Update your code to include many=True when dumping, and use result.data to get the clean serialized list:

data = MasterInventoryBatch.query.filter_by(party_id=party_id).all()
# Add many=True to handle the list of inventory objects
result = inventorysbatch_schema.dump(data, many=True)
return { 
    "genericResponse": generic_response(responsecode.GET_BATCH_SUCCESS, "True", responsemessage.GET_BATCH_SUCCESS), 
    "inventory": result.data  # Extract the clean serialized data
}

For Marshmallow 2.x Users

Marshmallow 2 doesn't return a MarshalResult—dump() gives you the serialized data directly. Just add many=True:

data = MasterInventoryBatch.query.filter_by(party_id=party_id).all()
result = inventorysbatch_schema.dump(data, many=True)
return { 
    "genericResponse": generic_response(responsecode.GET_BATCH_SUCCESS, "True", responsemessage.GET_BATCH_SUCCESS), 
    "inventory": result
}

Why This Works

  • many=True tells Marshmallow to serialize each item in the list individually, producing a flat array of objects instead of the broken nested structure.
  • result.data (in Marshmallow 3+) pulls just the serialized data from the MarshalResult object, avoiding any extra metadata that caused the stray empty object.

After this change, your response will match the expected structure:

{ 
    "genericResponse": { 
        "apiStatusMessage": "GET_BATCH_SUCCESS", 
        "apiSuccessStatus": "True", 
        "code": 16002, 
        "newToken": "null", 
        "newTokenGenerated": "false" 
    }, 
    "inventory":[ {},{},{},{},.... ] 
}

内容的提问来源于stack exchange,提问作者Ujjwal Khandelwal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:49:10