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

如何将Python数组记录赋值给REST请求体的constraints参数

问题与解决方案

问题

我有如下Python列表:

[
 {'type': 'A1'},
 {
   'filter': {
      'type': 'A2',
      'data': [{'key': 'name_1', 'value': 'a'}, {'key': 'name_2', 'value': 'a'}]
   }
 },
 {
   'filter': {
      'type': 'A2',
      'data': [{'key': 'name_1', 'value': 'b'}, {'key': 'name_2', 'value': 'b'}]
   }
 }
]

需要将其转换为REST请求体中名为constraints的参数,目标形式如下:

constraints = {
  'type': 'A1',
  'filter': {
      'type': 'A2',
      'data': [{'key': 'name_1', 'value': 'a'}, {'key': 'name_2', 'value': 'a'}]
  },
  'filter': {
      'type': 'A2',
      'data': [{'key': 'name_1', 'value': 'b'}, {'key': 'name_2', 'value': 'b'}]
  }
}

关键注意点

Python字典不允许存在重复键,如果直接通过字典合并操作,后面的filter键会覆盖前面的,导致数据丢失。比如执行普通的字典更新,最终只会保留最后一个filter的值。

解决方案

1. 手动构造JSON字符串(适配服务端要求重复键的场景)

如果服务端明确要求请求体包含重复的filter键,可以绕过Python字典,直接构造符合要求的JSON字符串:

import json

original_list = [
 {'type': 'A1'},
 {
   'filter': {
      'type': 'A2',
      'data': [{'key': 'name_1', 'value': 'a'}, {'key': 'name_2', 'value': 'a'}]
   }
 },
 {
   'filter': {
      'type': 'A2',
      'data': [{'key': 'name_1', 'value': 'b'}, {'key': 'name_2', 'value': 'b'}]
   }
 }
]

# 拆分每个元素的JSON部分并拼接
json_segments = []
for item in original_list:
    # 转成JSON后去掉首尾的大括号
    json_segments.append(json.dumps(item)[1:-1])

# 拼接成完整的JSON字符串
constraints_json = "{" + ", ".join(json_segments) + "}"

# 发送请求时直接传递该字符串作为请求体
print(constraints_json)

输出的JSON字符串即为目标格式:

{"type": "A1", "filter": {"type": "A2", "data": [{"key": "name_1", "value": "a"}, {"key": "name_2", "value": "a"}]}, "filter": {"type": "A2", "data": [{"key": "name_1", "value": "b"}, {"key": "name_2", "value": "b"}]}}

2. 使用规范的数组格式(推荐)

重复键在JSON规范中是不推荐的,多数解析库会默认保留最后一个键值对。更合理的设计是将多个filter放入数组中,建议和服务端确认是否支持这种格式:

constraints = {
    'type': 'A1',
    'filters': [
        {'type': 'A2', 'data': [{'key': 'name_1', 'value': 'a'}, {'key': 'name_2', 'value': 'a'}]},
        {'type': 'A2', 'data': [{'key': 'name_1', 'value': 'b'}, {'key': 'name_2', 'value': 'b'}]}
    ]
}

这种格式符合常规的API设计规范,也能完美适配Python字典的特性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 18:58:05