db_import.py 1.89 KB
import json
import sqlite3

conn = sqlite3.connect('db.sqlite3')

def byteify(input):
    if isinstance(input, dict):
        return {byteify(key):byteify(value) for key,value in input.iteritems()}
    elif isinstance(input, list):
        return [byteify(element) for element in input]
    elif isinstance(input, unicode):
        return input.encode('utf-8')
    else:
        return input

def import_fortunes(conn):
    fortune_file = 'fortunes.json'
    

    json_data=open(fortune_file).read()
    data = json.loads(json_data)

    c = conn.cursor()

    for fortune in data:
        try:
            c.execute("INSERT INTO fortunes (fortune, date_added) VALUES (?,'2016/01/18 00:00:00')", (fortune,))
        except Exception as e:
            print(e)
            pass
    conn.commit()

def import_jokes(conn):
    joke_file = 'jokes.json'
    

    json_data=open(joke_file).read()
    data = json.loads(json_data)

    c = conn.cursor()

    for joke in data:
        try:
            c.execute("INSERT INTO jokes (joke, date_added) VALUES (?,'2016/01/18 00:00:00')", (joke,))
        except Exception as e:
            print(e)
            pass
    conn.commit()

def import_messages(conn):
    deliveries_file = 'deliveries.json'

    json_data=open(deliveries_file).read()
    data = json.loads(json_data)

    c = conn.cursor()

    for username in data:
        print("Username: %s" % username)
        for author in data[username]:
            try:
                c.execute("INSERT INTO messages (message, delivery_time, channel, message_from, message_to, user_id) VALUES (?, ?, ?, ?, ?, ?)", (data[username][author]['message'], data[username][author]['delivery_time'],data[username][author]['channel'], author, username, data[username][author]['user_id']))
            except Exception as e:
                print(e)
                pass
    conn.commit()

import_jokes(conn)
import_fortunes(conn)
import_messages(conn)