Home > Software engineering >  writerow() with lists from JSON
writerow() with lists from JSON

Time:07-14

I have the following information extracted from a JSON and saved on a variables. The variables and its information are:

tickets = ['DC-830', 'DC-463’, ' DC-631’]

duration = ['5h 3m', '1h 7m' , ‘3h 4m'] 

When I use writerow() if the JSON has only one value for example, tickets = 'DC-830', I am able to save the information in a csv file. However, if it has 2 or more values it writes the information in the same row.

This is what I get:

Ticket | Duration

['DC-830', 'DC-463’, ' DC-631’] | ['5h 3m', '1h 7m' , ‘3h 4m'] 

Instead I need something like this:

Ticket | Duration

DC-830 | 5h 3m

DC-463 | 1h 7m

DC-631 | 3h 4m   

This is the code:

issues_test=s_json[['issues'][0]]
tickets,duration=[],[]
for item in issues_test:
    tickets.append(item['key'])
    duration.append(item['fields']['customfield_154'])

header = ['Ticket', 'Duration']
with open('P1_6.7.csv', 'a') as arc:
    writer = csv.writer(arc)
    writer.writerow(header)
    writer.writerow([tickets, duration])
    

CodePudding user response:

As the singular name suggests, writerow() just writes one row. The argument should be a list of strings or numbers. You're giving it a 2-dimensional list, and expecting it to pair them up and write each pair to a separate row.

To write multiple rows, use writerows() (notice the plural in the name). You can use zip() to pair up the elements of the two lists.

writer.writerows(zip(tickets, duration))
  • Related