0

Trying to insert data into database but I keep getting this error:

Traceback (most recent call last):
  File "business.py", line 25, in <module>
    data = fetch_data(con)
  File "business.py", line 18, in fetch_data
   result.append((entry['address'], entry['postalcode'],
KeyError: 'address'

Still new to python and coding. Appreciate your help, folks!

What I have so far:

import requests
import sqlite3

URL = 'http://url/url/url/{}.json'
def fetch_data(con):
    cur = con.cursor()
    cur.execute("SELECT identifier FROM restaurant WHERE res_creditnote = 'No' LIMIT 6")
    result = []
    for row in cur:
        r = requests.get(URL.format(row[0]))
        entry = r.json()
        result.append((entry['address'], entry['postalcode'],
                       entry['postal'], entry['statenumber'], entry['state'],
                       entry['countrycode'], entry['country']))
    return result

con = sqlite3.connect("business.db")
data = fetch_data(con)
cur = con.cursor()
cur.executemany('INSERT INTO hotel (address, postalcode, '
                'postal, statenumber, state, '
                'countrycode, country) VALUES (?, ?, ?, ?, ?, ?, ?);', data)
con.commit()
con.close()

EDIT

I try to fetch json data like this:

"businessaddress":{"address":"Stockholm road 11","postalcode":"045432","postal":"Stockholm","statenumber":"45141","state":"Stockholm","countrycode":"SW","country":"Sweden"}
2
  • 1
    What are you confused about? The error is telling you that the JSON you have downloaded does not contain an "address" key. Commented Apr 14, 2018 at 18:58
  • @DanielRoseman Please, see edit above. Commented Apr 14, 2018 at 19:15

2 Answers 2

1

Your data appears to a dictionary containing a key "businessaddress" which itself is a dictionary containing the other keys. So you need to access it that way, either via entry['businessaddress']['address'] etc or by assigning the inner dictionary to a temporary variable and using that:

entry = r.json()['businessaddress']
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, Daniel! Do you have time to chat in a private room? I have a few other important questions I really want to ask you about. I do not know how to invite you to a private chat. That is if you are available, thanks.
1

It has nothing to do with SQL, but with your dictionary called entry. Apparently the JSON you're retrieving does not have a address key in it. You can try debugging by printing then entry dictionary after this line entry = r.json()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.