Python -向JSON响应中的每个对象插入新的键值对

t3psigkw  于 2023-08-08  发布在  Python
关注(0)|答案(1)|浏览(115)

我有这个代码转换JSON响应,我想插入标签,通道和成员到每个对象。

import pandas as pd
import requests

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!')
            
            search_results = result['records']

            for item in search_results:
                item["tag"] = tag
                item["channel"] = channel
                item["member_id"] = member_id
            results.extend(search_results)         
df = pd.DataFrame(search_results)   
print(df.head(5))

字符串
但我一直得到这个错误:

item["tag"] = tag
TypeError: 'str' object does not support item assignment

**我已经解决了这个问题。

vxbzzdmp

vxbzzdmp1#

问题在于从requests.post()调用中获得的JSON响应。如果response.json()返回字符串而不是字典
如果响应是一个正确格式的JSON字符串,response.json()应该返回dictionary。

import pandas as pd
import requests

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}'}

search_results_all = []

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!')
            
            search_results = result['records']

            for item in search_results:
                item["tag"] = tag
                item["channel"] = channel
                item["member"] = member_id  # "assignee_id" to "member"
            
            search_results_all.extend(search_results)

df = pd.DataFrame(search_results_all)   
print(df.head(5))

字符串

相关问题