Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Finished

Bug when decoding non utf-8 characters
  • Loading branch information...
commit 66956753e5c9f099fbe2d15bb5c9c1cdaac2c79d 1 parent f4b50d7
Damien Firmenich damienfir authored
Showing with 75 additions and 2 deletions.
  1. +8 −2 README
  2. +67 −0 mysql2json.py
10 README
View
@@ -1,5 +1,11 @@
-# mysql2json
+mysql2json
+==========
Small tool to help converting a MySQL database to json
-usage: mysql2json address db user pwd
+usage: mysql2json address db user pwd
+
+Depedencies
+-----------
+- Python 2.6
+- mysql-python
67 mysql2json.py
View
@@ -0,0 +1,67 @@
+import sys
+import json
+import MySQLdb
+
+host = 'localhost'
+user = 'damienfir'
+pwd = 'inside'
+db_name = 'damienfir_tripin'
+
+class mysql:
+ def __init__(self):
+ self.connect()
+ self.tables = {}
+ self.json = ''
+
+ def connect(self):
+ db = MySQLdb.connect(host=host, user=user, passwd=pwd, db=db_name)
+ self.c = db.cursor()
+
+ def get_tables(self):
+ self.c.execute('SHOW TABLES')
+ for table in self.c.fetchall():
+ self.tables[table[0]] = []
+
+ def get_fields(self, table):
+ sql = 'DESCRIBE %s'
+ self.c.execute(sql % table)
+ ret = []
+ for row in self.c.fetchall():
+ ret.append(row[0])
+ return ret
+
+ def get_entries(self):
+ sql = 'SELECT %s FROM %s'
+ for table in self.tables.iterkeys():
+ cols = self.get_fields(table)
+ self.c.execute(sql % (','.join(cols), table))
+ for row in self.c.fetchall():
+ item = {}
+ for i in range(0,len(cols)):
+ try:
+ item[cols[i]] = str(row[i])
+ except:
+ print row[i]
+ self.tables[table].append(item)
+
+ def to_json(self):
+ try:
+ self.json = json.dumps(self.tables)
+ except UnicodeDecodeError as e:
+ print 'json error:'
+ print e
+ return self.json
+
+ def export(self):
+ if not self.c:
+ self.connect()
+ self.get_tables()
+ self.get_entries()
+ return self.to_json()
+
+def main():
+ sql = mysql()
+ print sql.export()
+
+if __name__ == '__main__':
+ main()
Please sign in to comment.
Something went wrong with that request. Please try again.