3

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')

3 Answers 3

4

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

df=pd.read_json("temp.json")
Sign up to request clarification or add additional context in comments.

Comments

4

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')

Comments

1
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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.