Hi all,
I have a simple problem. I am trying to get data from an API using a python script and add it to a database. preferably sqlite3 for ease of access. I am trying to get the code to decide the columns and add data to the row, without me explicitly having to do so.
my code is written below:
import json
import urllib
import sqlite3
serviceurl='<Enter API here>'
while True:
print ''
connection=urllib.urlopen(serviceurl)
db=sqlite3.connect('TD.db')
data = connection.read()
print data[:250]
headers = connection.info().dict
print headers
js = json.loads(data)
someitem=js.itervalues().next()
columns=list(someitem.keys())
query = query.format(",".join(columns), ",?" * len(columns))
for data in js.iteritems():
keys = (tuple(data[c] for c in columns))
c = db.cursor()
c.execute(query)
c.close()
What I have tried:
I have tried this code with the following error:
columns=list(someitem.keys())
AttributeError: 'unicode' object has no attribute 'keys'
I am getting data out of the API because given the following command, I am getting results
print json.dumps(js, indent=4)
There has to be an easier way of doing it, but I can't hardcode the columns, I need it to dynamically make columns from the dumps and then add data to the row. Any suggestions?