如何使用Python将CSV转换为JSON?

时间:2018-11-15 06:58:57

标签: python json pandas csv

我需要使用下面指定的python脚本将data.csv文件转换为“ ExpectedJsonFile.json”文件。但是我没有做到这一点。如下指定了Python脚本“ csvjs.py”。

import pandas as pd
from itertools import groupby
from collections import OrderedDict
import json

df = pd.read_csv('data8.csv', dtype={
            "Source" : str,
            "Template": str,
            "ConfigurationSetName": str,
       })

 results = []

for (Source, Template, ConfigurationSetName), bag in df.groupby      (["Source", "Template", "ConfigurationSetName"]):
   contents_df = bag.drop(["Source", "Template", "ConfigurationSetName"], axis=1)
Destinations = [OrderedDict(row) for i,row in contents_df.iterrows()]
results.append(OrderedDict([("Source", Source),
                            ("Template", Template),
                            ("ConfigurationSetName", ConfigurationSetName),
                            ("Destinations", Destinations)]))

print json.dumps(results[0], indent=4)
with open('ExpectedJsonFile.json', 'w') as outfile:
    outfile.write(json.dumps(results[0], indent=4))
data.csv中的

数据如下所示。

 Source,Template,ConfigurationSetName,ToAddresses,ReplacementTemplateData
 demo@example.com,MyTemplate,noreply,customer1@gmail.com,customer1
 demo@example.com,MyTemplate,noreply,customer2@gmail.com,customer2

当我运行“ python csvjs.py”时

{
    "Source": "demo@example.com",
    "Template": "MyTemplate",
    "ConfigurationSetName": "noreply",
    "Destinations": [
        {
            "ToAddresses": "customer1@gmail.com",
            "ReplacementTemplateData": "customer"
        },
        {
            "ToAddresses": "customer2@gmail.com",
            "ReplacementTemplateData": "customer2"
        }
    ]
}

但是我的预期输出如下

{
  "Source":"demo@example.com",
  "Template":"MyTemplate",
  "ConfigurationSetName": "noreply",
  "Destinations":[
    {
      "Destination":{
        "ToAddresses":[
        "customer1@gmail.com"
       ]
    },
      "ReplacementTemplateData":"{ \"name\":\"customer1\" }"
    },
    {
      "Destination":{ 
        "ToAddresses":[
        "customer2@gmail.com"
       ]
    },
     "ReplacementTemplateData":"{ \"name\":\"customer2\" }"
    },
    {
      "Destination":{
       "ToAddresses":[
       "customer3@gmail.com"
     ]
    },
  "ReplacementTemplateData":"{}"
 }
 ],
 "DefaultTemplateData":"{ \"name\":\"friend\" }"
}

我的模板如下所示

{
  "Template": {
  "TemplateName": "MyTemplate",
  "SubjectPart": "Greetings, {{Name}}!",
  "HtmlPart": "<h1>Hello {{Name}},</h1><p>Your favorite animal is cat.</p>",
  "TextPart": "Dear {{Name}},\r\nYour favorite animal is cat."
  }
}

1 个答案:

答案 0 :(得分:0)

通过更改此行代码,我获得了部分成功

contents_df = bag.drop(["Source", "Template", "ConfigurationSetName", "ToAddresses", "ReplacementTemplateData"], axis=1)

现在产生的输出看起来像这样。

{
  "Source":"demo@example.com",
  "Template":"MyTemplate",
  "ConfigurationSetName": "noreply",
  "Destinations":[
{
  "Destination":{
    "ToAddresses":"customer1@gmail.com"
   }
 },
 {
   "Destination":{ 
    "ToAddresses":"customer2@gmail.com"
        }
        }
    ]
}