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

Python中移除JSON特定外层方括号及规范生成JSON的方法

问题描述

当前生成的JSON格式如下:

{    
    "data": {        
        "type": "shipments",        
        "attributes": [            
            {                
                "shipment_tracking_number": "TRACK007",                
                "shipment_carrier": "AusPost",                
                "line_items_ids": [                    
                    1,                    
                    2                
                ]            
            }        
        ]    
    }
}

需要将attributes字段的外层方括号移除,得到以下目标格式:

{    
    "data": {        
        "type": "shipments",        
        "attributes": {            
            "shipment_tracking_number": "TRACK007",            
            "shipment_carrier": "AusPost",            
            "line_items_ids": [                
                1,                
                2            
            ]        
        }    
    }
}

生成该JSON的Python代码如下:

...
dfpush = dfall[['shipment_tracking_number','shipment_carrier','line_items_ids']].where(df['invoice_id'] == uniquevalue)
dfpush = dfpush.dropna(subset='shipment_tracking_number')
dfjson = dfpush.to_dict('records')
jsonpush = json.dumps({"data":{"type": "shipments", "attributes": dfjson }}, indent=4)

希望从生成源头直接得到正确格式的JSON,而非事后修改方括号。

解决方案

问题核心在于dfpush.to_dict('records')这一步:'records'参数会把DataFrame的每一行转换成字典,最终返回字典组成的列表,这就是attributes外层出现方括号的原因。

结合你的业务场景(筛选后dfpush应该只有一行数据),可以通过以下几种方式直接生成单个字典:

方法1:直接取列表第一个元素

修改代码中生成dfjson和jsonpush的部分:

dfjson = dfpush.to_dict('records')[0]  # 提取列表中的唯一字典元素
jsonpush = json.dumps({"data":{"type": "shipments", "attributes": dfjson }}, indent=4)

方法2:通过索引转换后取唯一值

如果不确定数据索引,可通过遍历提取唯一的行字典:

dfjson = dfpush.to_dict('index')
# 取字典中的第一个值(对应唯一的一行数据)
jsonpush = json.dumps({"data":{"type": "shipments", "attributes": next(iter(dfjson.values())) }}, indent=4)

方法3:先取单行数据再转字典

直接定位到DataFrame的唯一行,再转换为字典:

dfjson = dfpush.iloc[0].to_dict()
jsonpush = json.dumps({"data":{"type": "shipments", "attributes": dfjson }}, indent=4)

注意:如果业务场景中dfpush可能存在多行数据,需要先确认逻辑是否允许只取第一行,或者调整逻辑适配多行处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 20:18:28