Home > Enterprise >  I want to convert Json file to csv file using Pyhton
I want to convert Json file to csv file using Pyhton

Time:04-20

I have problem when i convert json file to csv i convert my csv file to json and it work but when i convert json file to csv file it don't work!

HERE MY PYTHON CODE

   with open('orders.json') as json_file:
    data = json.load(json_file)
 
    order_data = data['orders']

    # now we will open a file for writing
    data_file = open('data_file.csv', 'w')

    # create the csv writer object
    csv_writer = csv.writer(data_file)

    # Counter variable used for writing
    # headers to the CSV file
    count = 0

    for ord in order_data:
        if count == 0:

            # Writing headers of CSV file
            header = ord.keys()
            csv_writer.writerow(header)
            count  = 1

        # Writing data of CSV file
        csv_writer.writerow(ord.values())

    data_file.close()

and the output is like this

enter image description here

there null row on the csv file how to handle this problem?

and here the json file

enter image description here

CodePudding user response:

In Python 3 the required syntax changed and the csv module now works with text mode 'w', but also needs the newline='' (empty string) parameter to suppress Windows line translation (see documentation links below).

with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:
    writer = csv.writer(outfile)
  • Related