Python调用PUT接口提交Excel数据报JSON解析错误解决方法
错误原因
你的代码存在3个核心问题,直接触发报错或请求不符合接口要求:
- 类型不匹配触发首个报错:接口要求
itemId字段为字符串类型,你从Excel读取的Id是数值类型,JSON序列化后会传数字给接口,触发cannot unmarshal number into Go struct field PutPriceRequest.itemId of type string错误。 - 请求体结构完全不符合接口规范:
- 你在字典中重复定义
listPrice键,Python字典同键名后面的值会覆盖前面的值,导致顶层listPrice字段值不符合预期 - 你将属于
fixedPrices数组内的字段(tradePolicyId、value、固定价对应的listPrice、minQuantity、时间范围字段)全部平铺在请求体最外层,接口无法识别 from、to时间字段是嵌套在fixedPrices元素下的dateRange对象中的,不属于顶层字段
- 你在字典中重复定义
- 无意义的类型转换:你把所有数值类字段(
markup、basePrice、costPrice等)都转成了字符串,对照接口示例这些字段要求是数值类型,转字符串后会触发新的类型错误。 - 你后续修改时直接删掉
itemId字段的操作是错误的,接口明确要求该字段存在且为字符串类型。
修复方案
严格对照接口定义的结构构造请求,修正字段类型即可,修复后的核心代码如下:
for s, Id in enumerate(spreed_sheet["itemId"]): # 单独将itemId转为字符串,匹配接口类型要求 item_id = str(Id) # 数值类字段保留对应数值类型,不要转字符串 top_markup = spreed_sheet.loc[s, "markup"] top_list_price = float(spreed_sheet.loc[s, "listPrice"]) top_base_price = float(spreed_sheet.loc[s, "basePrice"]) top_cost_price = int(spreed_sheet.loc[s, "costPrice"]) # 固定价格数组内的字段 policy_id = str(int(spreed_sheet.loc[s, "tradePolicyId"])) fix_value = float(spreed_sheet.loc[s, "value"]) fix_list_price = int(spreed_sheet.loc[s, "listPrice"]) fix_min_qty = int(spreed_sheet.loc[s, "minQuantity"]) range_from = str(spreed_sheet.loc[s, "from"]) range_to = str(spreed_sheet.loc[s, "to"]) # 严格按照接口嵌套结构构造请求体 payload = { "itemId": item_id, "markup": top_markup, "listPrice": top_list_price, "basePrice": top_base_price, "costPrice": top_cost_price, "fixedPrices": [ { "tradePolicyId": policy_id, "value": fix_value, "listPrice": fix_list_price, "minQuantity": fix_min_qty, "dateRange": { "from": range_from, "to": range_to } } ] } url = f"https://myapi/myaccountname/pricing/prices/{item_id}" response = requests.put(url, headers=headers, json=payload) print(response.text) # 增加状态码判断,避免请求失败时直接解析json报错 if response.ok: resp_data = response.json() else: print(f"请求异常,状态码:{response.status_code}")
补充说明
- 如果单条商品对应多个固定价格策略,直接在
fixedPrices数组中追加对应结构的对象即可,和官方给出的示例结构保持一致。 - 如果接口要求时间字段是ISO标准格式,需要先把Excel读取到的时间值格式化为
YYYY-MM-DDTHH:MM:SSZ的形式再传入。
内容的提问来源于stack exchange,提问作者LaraF
相关产品推荐
相关产品推荐

