STEIN
STEIN

Reputation: 303

Inserting json into postgress database - Seeing TypeError: list indices must be integers or slices, not list

I am trying to insert json into posgtres DB but seeing this error:

data = response.json()[['data']]

TypeError: list indices must be integers or slices, not list

def main():
headers = {

response = requests.get('https://example-api.com/en/api/v1')
data = response.json()[['data']]

 fields = [
        'dateUtc',
        'countryCode',
        'name',
        'potency',
        'previous',
        'unit',
        'volatility'
]

conn = psycopg2.connect(conn_string)
cursor = conn.cursor()


for item in data:
    my_data = [item[field] for field in fields]
    # need a placeholder (%s) for each variable
    # refer to postgres docs on INSERT statement on how to specify order
    cursor.execute("INSERT INTO ecoonomic_calendar VALUES (%s, %s, %s,%s,%s,%s,%s,)",(my_data))


# commit changes
conn.commit()
# Close the connection
conn.close()

 if __name__ == '__main__':
 main()

This is an example of the JSON

'id': 'a3820f1a-44dd-4b09-9908-3550ce178e42', 'eventId': 'c96c0ac0-2879-4778-b4c1-5574325ba212', 'dateUtc': '2020-01-03T00:01:00Z', 'periodDateUtc': '2019-11-01T00:00:00Z', 'periodType': 'MONTH', 'actual': -0.4, 'revised': None, 'consensus': -0.5, 'ratioDeviation': None, 'previous': -0.5, 'isBetterThanExpected': True, 'name': 'BRC Shop Price Index (YoY)', 'countryCode': 'UK', 'currencyCode': 'GBP', 'unit': '%', 'potency': 'ZERO', 'volatility': 'LOW', 'isAllDay': False, 'isTentative': False, 'isPreliminary': False, 'isReport': False, 'isSpeech': False},

Upvotes: 0

Views: 145

Answers (1)

gold_cy
gold_cy

Reputation: 14236

The error message is trying to tell you what you are doing wrong

TypeError: list indices must be integers or slices, not list

It's saying that you can index a list with either integers or slices, nothing else. In your code you are trying to index using a list, specifically [['data']]. It should simply be ['data'], you have extra brackets around it. Then that piece of code becomes

data = response.json()['data']

Upvotes: 1

Related Questions