Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. import mysql.connector
  2. import json
  3. import csv
  4.  
  5. def flatten_json(y):
  6. out = {}
  7.  
  8. def flatten(x, name=''):
  9. if type(x) is dict:
  10. for a in x:
  11. flatten(x[a], name + a + '_')
  12. elif type(x) is list:
  13. i = 0
  14. for a in x:
  15. flatten(a, name + str(i) + '_')
  16. i += 1
  17. else:
  18. out[name[:-1]] = x
  19.  
  20. flatten(y)
  21. return out
  22.  
  23. def connection():
  24. db = mysql.connector.connect(user='user', password='password',
  25. host='host',
  26. database='db')
  27.  
  28. cursor = db.cursor()
  29.  
  30. query = ('SELECT id, data FROM table')
  31.  
  32. cursor.execute(query)
  33.  
  34. columns = cursor.description
  35. result = [{columns[index][0]:column for index, column in enumerate(value)} for value in cursor.fetchall()]
  36. return result
  37.  
  38. temp = connection()
  39. new_temp = []
  40. for ele in temp:
  41. id = ele["id"]
  42. to_conv = json.loads(ele["data"])
  43. to_conv = flatten_json(to_conv)
  44. to_conv["id"] = id
  45. new_temp.append(to_conv)
  46.  
  47.  
  48. keys = new_temp[0].keys()
  49. with open('output.csv', 'w') as output_file:
  50. dict_writer = csv.DictWriter(output_file, keys)
  51. dict_writer.writeheader()
  52. dict_writer.writerows(new_temp)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement