Typeerror: string indices must be integers - PYTHON

Asked

Viewed 14,386 times

1

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 structuring.

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')
  • Based on the error I believe that instead of putting the name of the field as web_id you must set the input of this field to 0 for the first attribute within json, 1 for the second and so on.

  • Hi @Lucasduete, thanks for the explanation. Loaded the database, but with some information that is not connected that column of json. Can you explain to me how I identify the index of each field?

  • Open the json in any text editor or display it in the terminal itself, then you look at the input of the field according to that logic: 0 for the first, 1 for the second and continue

  • @Lucasduete The return I got: {'lists': [{'id': ', 'web_id': 'name': , 'contact': {'company': , 'address1': , 'address2': ', 'city': , 'state':, 'zip': 'country': 'BR', 'phone': '}, Following the logic I would have to consider 1 and 2. In doing so, he inserted a letter in the web_id column and a letter in the column.

  • The problem mentioned in the question seems to have been fixed, it seems to be something else, if the json attributes have a value and it is displaying another you will have to review your code to see if it is not displaying wrong

  • @Maursb according to the error you are trying to access elements of a list as if it were a dictionary, it would be interesting for you to supplement the question with a part of the json file you are getting from the API.

Show 1 more comment

1 answer

1


According to your commenting, the JSON 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 JSON cited above. Thus, info will be a dictionary in Python and when you browse a dictionary with the loop for, you only go through the keys, not the values. That is, do for infos in info will make infos be the string "lists". To access a position of a string is accepted only numeric indexes, but you used a string, infos['web_id'], which explains the error obtained.

So how do you try to access the key web_id, believe that you are iterating the wrong object. As, in JSON, the key "lists" refers to a list of objects that hold the key web_id, I believe that’s the structure 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, can do what you want.

  • Anderson, thank you so much for the explanation!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.