如何使用Python在sqlite3表中转换json转储 [英] How do I convert json dump in sqlite3 table using Python
问题描述
大家好,
我有一个简单的问题。我试图使用python脚本从API获取数据并将其添加到数据库。最好是sqlite3以便于访问。我试图让代码来决定列并将数据添加到行中,而我没有明确地这样做。
我的代码如下:
import json
import urllib
import sqlite3
serviceurl = ' <在这里输入API> ;'
while True:
print ' '
connection = urllib.urlopen(serviceurl)
db = sqlite3.connect(' TD.db')
data = connection.read()
打印数据[:< span class =code-digit> 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()
我的尝试:
我尝试了以下错误的代码:
columns = list(someitem.keys())
AttributeError:'unicode'对象没有属性'keys'
我从API获取数据,因为给出以下命令,我得到的结果
print json.dumps(js,indent = 4 )
必须有一种更简单的方法,但我无法对列进行硬编码,我需要它来动态制作列中的列umps然后将数据添加到行。有任何建议吗?
请参阅 python 2.7 - 在JSON中查找值 - 堆栈溢出 [ ^ ]。
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?
See python 2.7 - Finding values in JSON - Stack Overflow[^].
这篇关于如何使用Python在sqlite3表中转换json转储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!