我有一个用例,我需要为数据文件中的每个个人生成一个JSON有效负载。每个数据文件将具有与之关联的配置文件。数据文件和相应的配置文件看起来像这样。
文件1(数据文件):
Employee ID,First Name,Last Name,Email
E1000,Manas,Jani,jam@xyz.com
E2000,Jim,Kong,jik@xyz.com
E3000,Olila,Jayavarman,olj@xyz.com
E4000,Lisa,Kopkingg,lik@xyz.com
E5000,Kishore,Pindhar,kip@xyz.com
E6000,Gobi,Nadar,gon@xyz.com
文件2(配置文件):
Input_file_column_name,Config_file_column_name,Value
Employee_ID,employee_Id,idTypeCode:001
First Name,first_Name
Last Name,last_Name
Email,email_Address
EntityID,entity_Id,01
如您所见,数据文件中的每个元素都位于配置文件中。配置文件包含根据JSON有效负载应命名字段的实际规则。另外,可能存在带有相关值的字段,需要将其放入JSON有效负载中才能传递给构建的API。
input_file_column_name 是输入数据文件中的名称,但是JSON有效负载将采用 config_file_column_name 的列名。
这是我发布JSON请求的样子:
{"IndividualInfo":[{"employee_Id":"E1000","first_Name":"Manas","last_Name":"Jani","email_Address":"jam@xyz.com","entity_Id":01,"idTypeCode":001},{"employee_Id":"E2000","first_Name":"Jim","last_Name":"Kong","email_Address":"jik@xyz.com","entity_Id":01,"idTypeCode":001},{"employee_Id":"E3000","first_Name":"Olila","last_Name":"Jayavarman","email_Address":"olj@xyz.com","entity_Id":01,"idTypeCode":001},{"employee_Id":"E4000","first_Name":"Lisa","last_Name":"Kopkingg","email_Address":"lik@xyz.com","entity_Id":01,"idTypeCode":001},{"employee_Id":"E5000","first_Name":"Kishore","last_Name":"Pindhar","email_Address":"kip@xyz.com","entity_Id":01,"idTypeCode":001},{"employee_Id":"E6000","first_Name":"Gobi","last_Name":"Nadar","email_Address":"gon@xyz.com","entity_Id":01,"idTypeCode":001}]}
一旦我从数据文件生成有效载荷,并添加了填充了 VALUE 字段的那些额外元素,我将无法理解如何替换密钥。任何建议都会很有帮助。
这就是我所使用的代码:
import json
import requests
import pandas as pd
file1='Onboarding_members.txt'
df = pd.read_csv(open(file1))
#print df.to_json(orient='records')
print df
file2='Onboarding_config.txt'
df1=pd.read_csv(open(file2))
#saved_column=df1['Config_file_name']
#print saved_column
print df1
df.columns = df.columns.map(df1.set_index('Input_file_name')['Config_file_name'].get)
#df2=df.rename(columns=df1.set_index('Input_file_name')['Config_file_name'], inplace=True)
print df
谢谢!
答案 0 :(得分:0)
我不是Python 2.X的专家,但是下面的代码片段可以帮助您入门。 希望以此片段为起点,可以根据自己的需要对其进行微调。
我正在使用的CSV源:
src.csv
Employee ID,First Name,Last Name,Email
E1000,Manas,Jani,jam@xyz.com
E2000,Jim,Kong,jik@xyz.com
E3000,Olila,Jayavarman,olj@xyz.com
E4000,Lisa,Kopkingg,lik@xyz.com
E5000,Kishore,Pindhar,kip@xyz.com
E6000,Gobi,Nadar,gon@xyz.com
以下是解析csv,为每个人创建字典并将它们包装到列表中的代码:
example.py
import csv
import io
path = "/tmp/csvTst/src.csv"
employees = []
with io.open(path, newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
employees.append(
{
"Employee ID": row['Employee ID'],
"First Name": row['First Name'],
"Last Name": row['Last Name'],
"Email": row['Email']
}
)
print employees
要使用请求库进行发布,您无需导入json。您的要求将如下所示:
for employee in employees:
requests.post("https://my-site.com/api/users/", json=employee)
当然,您可以通过自动将csv的第一行分配为字典的键而不用手动对其进行硬编码来使此操作更为复杂,但是我想使代码段尽可能简单。