【问题标题】:Python to Parse JSON and store list into SQLite TablePython 解析 JSON 并将列表存储到 SQLite 表中
【发布时间】:2016-01-06 18:11:38
【问题描述】:

目前,尝试将以下 list 项目导入 11 个不同的列(列表中的每个项目进入不同的列)。我认为问题的根源是我在python 脚本中使用的方法需要具有这种格式:[(1,2,3,...,11),(1,2,3,...,11)] 基本上是由括号分隔的行列表导致tuples。

我对代码的尝试:

import sqlite3
import json

lst = []
with open('data.json') as data_file:
    data = json.load(data_file)

for e in data:
    if e == 'participants':
        continue
        #participants_data=data['participants'][0]
        #print participants_data
        #for f in participants_data:
            # print f
            # print participants_data[f]    
    else:
        lst.append(data[e])
        # print e
        # print data[e]


conn = sqlite3.connect('somedbname.sqlite')
c = conn.cursor()
c.execute('''CREATE TABLE if not exists stocks33
             (col1 text, col2 text, col3 text, col4 text, col5 text, col6 text, col7 text, col8 text, col9 text, col10 text, col11 text)''')

c.executemany("INSERT INTO stocks33 VALUES (?,?,?,?,?,?,?,?,?,?,?)", lst)
conn.commit()
c.execute("select * from stocks33")
print(c.fetchall())

数据:

{
   "matchId": 1778839570,
   "region": "NA",
   "platformId": "NA1",
   "matchMode": "CLASSIC",
   "matchType": "MATCHED_GAME",
   "matchCreation": 1427867835805,
   "matchDuration": 3424,
   "queueType": "RANKED_SOLO_5x5",
   "mapId": 11,
   "season": "SEASON2015",
   "matchVersion": "5.6.0.194",
   "participants": [
      {
         "teamId": 100,
         "spell1Id": 4,
         "spell2Id": 11,
         "championId": 113,
         "highestAchievedSeasonTier": "GOLD"
      }
   ]
}

【问题讨论】:

  • 你得到了什么,你期待什么?

标签: python json parsing sqlite tuples


【解决方案1】:

我不确定我是否理解这个问题,但你可能是想说

c.execute("INSERT INTO stocks33 VALUES (?,?,?,?,?,?,?,?,?,?,?)", lst)

这会将单个列表插入数据库。

您提供了 1 个 JSON 字典,并且没有提及它们是否更多,或者它们是如何存储的(即与列表相同的 JSON 文件?)。如果要插入列表列表[[...],[...]],则使用executeall。否则你就做execute

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    相关资源
    最近更新 更多