我试图在PostgreSQL中插入一些JSON文件,但我对它有点陌生,我有一些问题。所以,我已经有了这些文件,这些文件是经过编码的,这里有一个简单的例子来说明我要做什么。在Postgres中创建一些表并在其中添加twitter信息。在
import json
import psycopg2
conn = psycopg2.connect("dbname='postgres' user='bilabial' host='localhost'")
cur = conn.cursor()
linenumber = 0
data = open('tweets_testing.json').read()
for line in data:
linenumber += 1
try:
str_line = line.strip()
vals = json.loads(str_line)
tweets = vals["text"]
cur.execute("CREATE TABLE tweetstext (text VARCHAR(255));")
cur.execute("INSERT INTO tweetstext (" + tweets+ ");")
conn.commit()
except KeyError:
break
所以我得到的错误是“TypeError:list index必须是整数,而不是str”。当我读到它的时候,我不太明白它的区别,所以任何帮助都将是非常感激的。在
vals的
type
是list
。 通过print "Type vals", type(vals)
检查vals
的类型演示:根据您的代码。在
^{pr2}$期望
vals
的type
应该是dict
,即dictionary。在你能剪切
str_line
变量的值结构吗?[编辑2]
根据我的说法,我们需要加载json文件的所有内容。在
但是代码会根据输入和逻辑而改变。在
相关问题 更多 >
编程相关推荐