Home > database >  How to convert list to Json after retrieve from database in Python?
How to convert list to Json after retrieve from database in Python?

Time:03-22

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

CodePudding user response:

Use an extend method to convert your tuple to an array

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

CodePudding user response:

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)
  • Related