Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:

C#
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
C#
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?
Posted
Updated 2-Mar-20 3:16am

1 solution

 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900