Skip to content Skip to sidebar Skip to footer

How To Convert JSON File Into CSV Using Python

I am trying to fetch the execution details of one user, and all those data i am capturing in a JSON and saving it , i want to convert this from JSON and write all the data from JSO

Solution 1:

It's simple.

    for result in resp:
        if count ==0:
            print("No Data to Read") 
            count+=1
        else:
        csvWriter.writerow(result.values)

It's unnecessary if.

    for result in resp:
        csvWriter.writerow(result.values)

Solution 2:

You can try with pandas, read the file with pandas.read_json and save it with .to_csv


Solution 3:

You are iterating through list and every list item is a dictionary . So instead of csvWriter.writerow(result.values)

you should

 csvWriter.writerow(result.keys())
 csvWriter.writerow(result.values())

you can write key , value pairs of dictionary as you wish in here. You can write "key1,key2" then next line "value1,value2". or create a header with keys before loop then write values in every line for each item in the list. See more examples on this link How do I write a Python dictionary to a csv file?

why do you skip the first item in the list and doing json to string and back to json again. You might want to check these again

response_value = response.json()
#<class 'list'>
response_value = json.dumps(response_value)
#<class 'str'>
resp = json.loads(response_value)
#<class 'list'>

Also, it might not be really good idea to share tokens and real urls in public domain


Post a Comment for "How To Convert JSON File Into CSV Using Python"