0

I have a database like this: enter image description here

When i retrieved this column and want to convert it to Json format like this:

cursor3 = conn.cursor()
cursor3.execute("select version()")
data = cursor3.fetchone()
cursor3.execute("SELECT headerdynamic FROM emailData ")
headerDynamic = cursor3.fetchall()
di = {i.split(':')[0]:i.split(':')[1] for i in headerDynamic}
js = json.dumps(di)
print(js)

It will prompt this error message:

di = {i.split(':')[0]:i.split(':')[1] for i in headerDynamic}
AttributeError: 'tuple' object has no attribute 'split'

Here is the print output of the headerDynamic

 [("'header1 : Subject', 'header2 :Text'",)] 

Does anyone know what im doing wrong here? Thanks

WEI ZHUANG GOH
  • 313
  • 1
  • 13
  • this might help u - https://stackoverflow.com/questions/3286525/return-sql-table-as-json-in-python – gil Mar 22 '22 at 07:11

2 Answers2

1

Use an extend method to convert your tuple to an array

x = []
for item in a:
    x.extend(item)
0

You can print out headerDynamic and see what kind of data is inside. Most likely, you will find tuple datatypes which cannot be splitted the way you try.

Iterate over your tuples (Not your Array which contains tuples!):

for i in ("'header1 : Subject', 'header2 :Text'",):
    # i is a string, which has your intended split function
    print(i)
  • Here is the print output `[("'header1 : Subject', 'header2 :Text'",), ("'header1 : Subject', 'header2 :Text'",)]` and the type is `list` – WEI ZHUANG GOH Mar 22 '22 at 07:30
  • Yes but inside the list, there are tuples; identified by the (,) syntax. –  Mar 22 '22 at 07:56