【发布时间】:2021-04-26 20:53:14
【问题描述】:
尝试将多个 json 文件转换为 1 个 csv 文件
尝试了2种方法,
第一个使用熊猫,
第二个使用 json 和 csv 编写器
关于我的 json
keys are unordered and some keys are different in every file
使用编写器编写代码
file_list=os.listdir('output')
count = 0
for file in file_list:
dict={}
file_path = "output/" + file
with open(file_path,'r') as f:
jsonData=json.load(f)
datafile=open('data.csv','a')
csv_writer = csv.writer(datafile)
if count == 0:
header = jsonData.keys()
csv_writer.writerow(header)
count += 1
csv_writer.writerow(jsonData.values())
if count == 1:
csv_writer.writerow(jsonData.values())
datafile.close()
问题
bcoz my data is unordered and different keys so in my csv file wrong value is coming under wrong header
使用 Pandas 编写代码
for file in file_list:
dict={}
file_path = "output/" + file
with open(file_path,'r') as f:
jsonData=json.load(f)
for j in jsonData:
dict.update({j:[jsonData[j]]})
df=pd.DataFrame(dict)
df.to_csv("hello.csv")
问题
i dont know how to append in pandas
so this is showing only 2 rows bcoz of my last json file i guess
在我的 json 中
【问题讨论】:
-
每个 json 文件是否应该在输出中占一行?您能否提供一两个简短的示例 json 文件,甚至可能是所有可能键的列表,它们应该出现在 csv 输出中?
-
标头
Solutions, account_number ,actual_reading_current, actual_reading_previous address, amount_due,值$7.90 72xxx06,,,, 16839,,, 16586 ,,, T B FAIR LAWN BORO NJ 07410 ,,,48.1 -
这是您想要的 csv 文件的标题?你能否也给我一个虚拟的json文件来测试?请使用文件共享服务或更改您的原始帖子,cmets 不允许大量格式化。
-
@ClF3 添加 json 数据