无法使用Python将JSON文件转换为CSV [英] Unable to convert JSON file to CSV using Python

查看:157
本文介绍了无法使用Python将JSON文件转换为CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将以下JSON文件转换为csv文件。



JSON文件

  [{
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:但是,我的Python代码下面给出错误消息TypeError:Expected String or Unicode。我可以知道如何修改我的程序以使其工作?

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


解决方案

您只需将地址字符串传递给 pd.read_json()

  df = pd.read_json(temp.json)


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

解决方案

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

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

这篇关于无法使用Python将JSON文件转换为CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆