简体   繁体   中英

convert json to csv using python pandas

How to convert the Json file to csv file using python pandas Reading file:

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

    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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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