-
Notifications
You must be signed in to change notification settings - Fork 0
/
json_to_db.py
63 lines (48 loc) · 1.53 KB
/
json_to_db.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#-*- coding: utf-8 -*-
import os, sys
### Get path of JSON file
if len(sys.argv) != 2:
sys.exit("expected json file")
json_file = sys.argv[1]
### SQL
from sqlobject import *
#~ mysql://user:password@host/database
#~ postgres://user@host/database
#~ sqlite:///full/path/to/database
sqlite_path = os.getcwd()
sqlite_file = "kamoulox.db"
sqlhub.processConnection = connectionForURI('sqlite://%s' %os.path.join(sqlite_path, sqlite_file))
# Schema
class Kamoulox(SQLObject):
pub_date = DateCol()
authors = StringCol()
source = StringCol()
url = StringCol()
title = StringCol()
content = StringCol()
# Let's create
Kamoulox.createTable(ifNotExists=True)
### Parse and insert
import json, time
json_data=open(json_file)
data = json.load(json_data)
json_data.close()
for idx, article in enumerate(data):
authors = article['AUTHORS'].encode("utf-8")
title = article['TITLE'].encode("utf-8")
content = article['CONTENT'].encode("utf-8")
url = article['URL']
source = article['SOURCE']
year = article['YEAR']
date = article['DATE']
if date:
try:
date = time.strptime(date, "%d/%m/%Y")
date = time.strftime("%Y-%m-%d", date)
except ValueError:
print '[ERROR] JSON : date value invalid : #%s : "%s" - "%s"' %(idx, date, title.decode("utf-8"))
date = None
else:
date = None
print '#%s - %s' %(idx, title)
Kamoulox(pub_date=date, authors=authors, source=source, url=url, title=title, content=content)