简体   繁体   English

使用 python pandas 将 json 转换为 csv

[英]convert json to csv using python pandas

How to convert the Json file to csv file using python pandas Reading file:如何使用 python pandas 读取文件将 Json 文件转换为 csv 文件:

with open('temp.txt') as f:
    content = f.read().replce('U','')
d=json.loads(content)

Input:输入:

 {"D":{
    "1":"66",
    "2":"77",
    "3":"3"
},"A":{
    "11":"166",
    "12":"177",
    "13":"13"
}}U
{"X":{
"2":"5",
"3":"4"}}U
{"E":{
"4":"55",
"6":"33"}}U

output csv file should be输出 csv 文件应该是

    D1,D2,D3,A11,A12,A13,X2,X3,E4,E6
66,77,3,166,177,13,NA,NA,NA,NA
NA,NA,NA,NA,NA,NA,5,4,NA,NA
NA,NA,NA,NA,NA,NA,NA,NA,55,33
import pandas as pd
import json

with open('test.json') as f:
    content = f.read().replace('U',',')[::-1].replace(',', '', 1)[::-1]
    content = '[{}]'.format(content)

l = json.loads(content)
d = [{k1+k2: v2 for k2,v2 in v1.items()} for x in l for k1,v1 in x.items()]

df = pd.DataFrame(d2, columns=[k for x in d for k in x.keys()])
print(df)

Output:输出:

    D1   D2   D3  A11  A12  A13   X2   X3   E4   E6
0   66   77    3  NaN  NaN  NaN  NaN  NaN  NaN  NaN
1  NaN  NaN  NaN  166  177   13  NaN  NaN  NaN  NaN
2  NaN  NaN  NaN  NaN  NaN  NaN    5    4  NaN  NaN
3  NaN  NaN  NaN  NaN  NaN  NaN  NaN  NaN   55   33

And to save to a CSV file: df.to_csv(filename, index=False)并保存到 CSV 文件: df.to_csv(filename, index=False)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM