【问题标题】:Django - how can i insert '.json' file to SQLite DB?Django - 我如何将“.json”文件插入 SQLite DB?
【发布时间】:2021-11-01 10:31:05
【问题描述】:

我的“.json 文件”喜欢

{
  "users": [
    {
      "userId": 1,
      "firstName": "AAAAA",
      "lastName": "as23",
      "phoneNumber": "123456",
      "emailAddress": "AAAAA@test.com",
      "homepage": "https://amogg.tistory.com/1"
    },
    {
      "userId": 2,
      "firstName": "BBBB",
      "lastName": "h5jdd",
      "phoneNumber": "123456",
      "homepage": "https://amogg.tistory.com/2"
    },
    {
      "userId": 3,
...

我正在谷歌上搜索,并尝试解决这个问题..但未解决。 所以我使用 pandas 和 sqlite3

import sqlite3 as db
import pandas as pd

df = pd.read_json('test.json')
con = db.connect('./test.db')

df.to_sql('test', con=con)

因此创建了数据库,但 .json 文件数据不保存在数据库中 如何解决这个问题...?

【问题讨论】:

    标签: python json django sqlite


    【解决方案1】:

    您必须事先创建表“test”,遍历 pandas 数据帧 df 并将记录一一插入到表中:

    import sqlite3 as db
    import pandas as pd
    
    df = pd.read_json('test.json', orient='index')
    con = db.connect('./test.db')
    cursor = con.cursor()
    cursor.execute('''create table test (userId int primary key,
                                         firstName text,
                                         lastName text,
                                         phoneNumber text,
                                         emailAddress text,
                                         homePage text)''')
    
    
    for index, row in df.iterrows():
        for element in row.iteritems():
            try:
                firstName = element[1]['firstName']
            except:
                firstName = ''
            try:
                lastName = element[1]['lastName']
            except:
                lastName = ''
            try:
                phoneNumber = element[1]['phoneNumber']
            except:
                phoneNumber = ''
            try:
                emailAddress = element[1]['emailAddress']
            except:
                emailAddress = ''
            try:
                homepage = element[1]['homepage']
            except:
                homepage = ''
    
            cursor.execute("INSERT INTO test VALUES (?,?,?,?,?,?)", (element[1]['userId'],
                                                                     firstName,
                                                                     lastName,
                                                                     phoneNumber,
                                                                     emailAddress,
                                                                     homepage))
    
    con.commit()
    con.close()
    

    由于并非所有记录的所有列都具有相同的有效值,因此您需要使用 try/except 验证列的存在,如果该列不存在于该行中,则存储一个空字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-28
      • 1970-01-01
      • 2013-02-07
      • 2012-02-07
      • 2021-05-28
      • 1970-01-01
      • 2012-02-10
      • 1970-01-01
      相关资源
      最近更新 更多