Python - Insert new key value pair to each object in a JSON response

95 views Asked by At

I have this code for transforming JSON response and I'd like to insert the tags, channels, and members into each object.

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))  

but I keep getting this error:

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

** I already fixed the issue.

1

There are 1 answers

2
Akhilesh Pandey On

Issue is with the JSON response you are getting from your requests.post() call. If response.json() returns a string instead of a dictionary

response.json() should return dictionary if the response is a correctly formed JSON string.

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))