0

I am transforming JSON like data to CSV and having a few issues.

The code is here:

import json
import csv

def parse_file(inputed_file):
    with open(input_file, 'r') as inputed_file:
        content = inputed_file.readlines()
        split_file = open('test.csv', 'w')

        for line in content:
            lines = line.split('\t')

            data = json.loads(lines[0])
            writer = csv.DictWriter(split_file, fieldnames = ["title", "firstname"], delimiter = ',')
            writer.writeheader()

The problem is this is adding a header on each row for the data, I want to only have the header displayed once. Then add this for the data to go below the headers:

writer.writerow(data)

I have looked at this and tried it but failed: How can I convert JSON to CSV?.

halfer
  • 19,824
  • 17
  • 99
  • 186
Sam
  • 1,207
  • 4
  • 26
  • 50

1 Answers1

0

Create the DictWriter outside the loop, and just call writer.writeheader() there. Then call writer.writerow() inside the loop.

def parse_file(inputed_file):
    with open(input_file, 'r') as inputed_file:
        content = inputed_file.readlines()
        split_file = open('test.csv', 'w')
        writer = csv.DictWriter(split_file, fieldnames = ["title", "firstname"], delimiter = ',')
        writer.writeheader()

        for line in content:
            lines = line.split('\t')
            data = json.loads(lines[0])
            writer.writerow(data)
Barmar
  • 741,623
  • 53
  • 500
  • 612