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

向JSON响应中每个对象插入键值对时遇TypeError错误

解决TypeError: 'str' object does not support item assignment问题

问题场景

我编写了一段Python代码,用于转换API返回的JSON响应,希望将tags、channels、members的对应值插入到响应的每个对象中。但运行代码时持续触发错误:item["tag"] = tag 抛出TypeError: 'str' object does not support item assignment。(已解决)

问题原因

报错的核心是search_results中的item并非可修改的字典类型,而是字符串。API返回的records数组里的元素是字符串格式,而非预期的字典结构,因此无法通过键值对方式为其添加新字段。

解决方案

  1. 类型校验与转换:如果item是JSON格式字符串,使用json.loads()将其转换为字典;若为其他字符串格式,需根据实际结构解析为字典。
  2. 修正DataFrame数据源:原代码最后用search_results创建DataFrame,只会保留最后一次循环的结果,应改用收集了所有结果的results列表。

修正后的代码

import pandas as pd
import requests
import json

members = [12321,21223,22131,23134]
tags = [6345,3456]
channels = ["abc","cde","fgh"]
access_token = "sample_token"

url = f"https://google.com/api/sample"
headers = {
    "Content-Type": "application/json",
    "Accept": "application/json",
    "Authorization": f'Basic {access_token}'}
results = []
for tag in tags:
    for channel in channels:
        for member_id in members:
            response = requests.post(url, headers=headers)
            result = response.json()
                            
            if 'records' not in result:
                print('No tickets found!')
                continue  # 无数据时跳过后续处理
            
            search_results = result['records']
            processed_items = []
            
            for item in search_results:
                # 处理字符串类型的item,转为字典
                if isinstance(item, str):
                    try:
                        item_dict = json.loads(item)
                    except json.JSONDecodeError:
                        print(f"无法解析无效字符串: {item}")
                        continue
                else:
                    item_dict = item.copy()  # 可选:避免修改原API返回对象
                
                # 添加目标字段
                item_dict["tag"] = tag
                item_dict["channel"] = channel
                item_dict["member_id"] = member_id
                processed_items.append(item_dict)
            
            results.extend(processed_items)         
df = pd.DataFrame(results)  # 基于所有结果创建DataFrame
print(df.head(5))  

额外注意事项

  • 优先打印search_results的类型和内容,确认API返回的records结构是否符合预期。
  • 添加异常处理,避免单个无效数据导致整个程序中断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 23:22:29