WEI ZHUANG GOH
WEI ZHUANG GOH

Reputation: 333

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

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

Upvotes: 0

Views: 100

Answers (2)

user18539642
user18539642

Reputation:

Use an extend method to convert your tuple to an array

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

Upvotes: 1

user18539237
user18539237

Reputation:

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)

Upvotes: 0

Related Questions