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.
– Lucas Duete
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?
– Maursb
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
– Lucas Duete
@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.
– Maursb
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
– Lucas Duete
@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.
– Camilo Santos