如何使用循环

时间:2019-07-16 16:59:46

标签: python json pandas

我喜欢将数据框转换为预格式json以在API中进行调用 我的数据框看起来像:

;First Name;Name;Country;Email
0;Paul;TRUC;FR;test@gmail,com
1;Henry;DEFAULT;US;test1@gmail.com
2;John;TEMP;GB;test2@gmail.com

我希望:

{"Adresse": [
    {
        "_ActionFlag": "create",
        "Id": "xxxxx-xxxx-xxxxx-xxxxx-xxxx",
        "Pays": "FR"
    },
 "Individu": [
     {
         "_ActionFlag": "create",
         "Id": "xxxxx-xxxx-xxxxx-xxxxx-xxxx",
         "First Name": "Paul",
         "Name": "TRUC",
         "Email": "test@gmail.com"
     },
     {
         "_ActionFlag": "create",
         "Id": "xxxxx-xxxx-xxxxx-xxxxx-xxxx",
         "First Name": "Henry",
         "Name": "DEFAULT",
         "Email": "test1@gmail.com"
     },
     {
         "_ActionFlag": "create",
         "Id": "xxxxx-xxxx-xxxxx-xxxxx-xxxx",
         "First Name": "John",
         "Name": "TEMP",
         "Email": "test2@gmail.com"
     }
  ]
}

1 个答案:

答案 0 :(得分:0)

将CSV读入DataFrame:

df = pd.read_csv(r'data/user.csv', header='infer', sep=';')

DataFrame看起来像:

Id  First Name  Name    Country Email
0   Paul        TRUC    FR      test@gmail,com
1   Henry       DEFAULT US      test1@gmail.com
2   John        TEMP    GB      test2@gmail.com

将DataFrame转换为json:

json = df.to_json(orient='records')

JSON如下:

'[{"Id":0,"First Name":"Paul","Name":"TRUC","Country":"FR","Email":"test@gmail,com"},{"Id":1,"First Name":"Henry","Name":"DEFAULT","Country":"US","Email":"test1@gmail.com"},{"Id":2,"First Name":"John","Name":"TEMP","Country":"GB","Email":"test2@gmail.com"}]'

在此处查看运行示例: