1

I have sql data in string form which I'm trying to convert to list.

sql = "(10001,'AEX','CCC','X12344','John, Doe','Not indicated','None','No','No','No','\r\n'),(10002,'AEX','CCC','X12344','John, Doe','Not indicated','None','No','No','No','\r\n')"

sql = sql.replace("(", "[")
sql = sql.replace(")", "]")


However when I try to convert it to list using list(), it breaks everything.

tomeda
  • 75
  • 1
  • 11

2 Answers2

1

Try using ast.literal_eval and a nested list comprehension:

>>> from ast import literal_eval as leval
>>> sql = "(10001,'AEX','CCC','X12344','John, Doe','Not indicated','None','No','No','No','\r\n'),(10002,'AEX','CCC','X12344','John, Doe','Not indicated','None','No','No','No','\r\n')"
>>> [[leval(x) for x in i.strip('()').replace(",'", "split'").split('split')[:-1]] for i in sql.replace('\r\n', '').replace('),(', ')split(').split('split')]
[[10001, 'AEX', 'CCC', 'X12344', 'John, Doe', 'Not indicated', 'None', 'No', 'No', 'No'], [10002, 'AEX', 'CCC', 'X12344', 'John, Doe', 'Not indicated', 'None', 'No', 'No', 'No']]
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

Simple solution using regex (re module in python) :

import re
sql = "(10001,'AEX','CCC','X12344','John, Doe','Not indicated','None','No','No','No','\r\n'),(10002,'AEX','CCC','X12344','John, Doe','Not indicated','None','No','No','No','\r\n')"
groups = re.findall('\([^()]*\)', sql)
lists = [list(eval(lst[:-6]+')')) for lst in groups]

'\([^()]*\)' regex to capture all the characters between all the parentheses (()).

lst[:-6]+')' to remove the trailing ,'\r\n') and append ) (to make a complete 'tuple string') so that eval runs smoothly and returns a tuple, then convert it to a list using list().

Jarvis
  • 8,494
  • 3
  • 27
  • 58