Unable to convert JSON file to CSV using Python

14,836

Solution 1

You just need to pass the address string to pd.read_json():

df=pd.read_json("temp.json")

Solution 2

You have not to use json module:

Try:

import pandas as pd

df=pd.read_json("temp.json")
print(df)
df.to_csv('results.csv')

Solution 3

import pandas as pd
df = pd.read_json('data.json')
df.to_csv('data.csv', index=False, columns=['title', 'subtitle', 'date', 'description'])

import pandas as pd
df = pd.read_csv("data.csv")
df = df[df.columns[:4]]
df.dropna(how='all')
df.to_json('data.json', orient='records')
Share:
14,836
Tsing
Author by

Tsing

Updated on June 29, 2022

Comments

  • Tsing
    Tsing almost 2 years

    I was trying to convert the below JSON file into a csv file.

    JSON file

    [{
    "SubmitID":1, "Worksheet":3, "UserID":65,
     "Q1":"395",
     "Q2":"2178",
     "Q3":"2699",
     "Q4":"1494"},{
     "SubmitID":2, "Worksheet":3, "UserID":65,
      "Q4":"1394"},{
     "SubmitID":3, "Worksheet":4, "UserID":65,
      "Q1":"1629",
      "Q2":"1950",
      "Q3":"0117",
      "Q4":"1816",
     "Empty":" "}]
    

    However, my Python code below gives the error message "TypeError: Expected String or Unicode". May I know how should I modify my program to make it work?

    import json
    import pandas as pd
    
    f2 = open('temp.json')
    useful_input = json.load(f2)
    df=pd.read_json(useful_input)
    print(df)
    df.to_csv('results.csv')