TypeError: string indices must be integers - PYTHON

0

When I try to list json, it is returning the error:

save.append ((infos ['web_id']) TypeError: string indices must be integers

Can you help me understand how this happened? I have little experience in python and it's basically the first API I'm designing.

import requests
import psycopg2

key = 'KEY'
url = 'URL'
head = {'anystring':'KEY'}

r = requests.get(url, auth=('USER',key))

conn = psycopg2.connect("dbname='DBNAME' user='USER' host='HOST' 
password='PASSWORD'")
insert = "INSERT INTO TABELA (web_id,name) VALUES"

info = r.json()

#print(info)

gravar=[]
for infos in info:
    gravar.append((infos['web_id'],
                   infos['name']
                   ) )        

if len(gravar) >0 :
    cur = conn.cursor()
    y = b','.join(cur.mogrify("(%s,%s)", x) for x in gravar)
    comando = insert + y.decode()
    try:
        cur.execute(comando)
        conn.commit()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)

    cur.close()
    print('Carga Completa')
else:
    conn.close()
    print('Nada a Inserir')
    
asked by anonymous 26.10.2018 / 03:42

1 answer

0

As per your comment , the JSON that you receive resembles:

{
    "lists": [
        {
            "id": "", 
            "web_id": "", 
            "name": "", 
            "contact": {
                "company": "", 
                "address1": "", 
                "address2": "", 
                "city": "", 
                "state":, 
                "zip": "", 
                "country": "BR", 
                "phone": ""
            }
        }
    ]
}

Considering the code below

info = r.json()

#print(info)

gravar=[]
for infos in info:
    gravar.append((infos['web_id'], infos['name']))

I will assume that info is the above JSON. This way, info will be a dictionary in Python, and when you scroll through a dictionary with the for loop, you go through only the keys, not the values. That is, doing for infos in info will cause infos to be the string "lists" . To access a position of a string only numeric indexes are accepted, but you used a string , infos['web_id'] , which explains the error.

So, as you try to access the web_id key, I believe you are iterating the wrong object. As in JSON, the "lists" key refers to a list of objects that have the web_id key, I believe this is the structure that you want to iterate, so:

for infos in info['lists']:
    gravar.append((infos['web_id'], infos['name']))

In this way, infos will be a dictionary with the keys web_id and name , being able to do what you want.

    
26.10.2018 / 14:25