这可能与Stackoverflow上的其他问题类似,但我找不到任何能提供我所需json结构的答案。
我希望能够获取一个csv文件,读取数据,将其转换为json,以便能够使用Freshdesk的API创建新客户。
要在Freshdesk中创建客户,我需要将数据转换为JSON。我需要的格式是:
info = {
'name': 'Test Customer',
'custom_fields': {
'company_reg_no' : '25865',
'phone' : '0113 12345678',
'date' : '2016-11-11',
'address' : """Some Address,
Some Road,
Some Where,
SM1 1AA"""
}
}
我可以打开CSV文件:
^{pr2}$我正在努力将其转换为JSON,尤其是必须将一些字段放在“custom_fields”键下。我试着建立一个列表或字典,然后打电话给:
^{3}$但我找不到正确的结构。
有什么想法吗?
谢谢
编辑-按要求填写完整代码,包括Rob的回答
import csv
import json
import requests
FRESHDESK_ENDPOINT = "https://xxxxxxxxxxxxxxx.freshdesk.com"
FRESHDESK_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
headers = {'Content-Type': 'application/json'}
dict_customers = []
with open('FDimport.csv', 'r') as csvfile:
reader = csv.DictReader(csvfile)
for csv_customer in reader:
dict_customer = {
'name':csv_customer['Name'],
'custom_fields': {
'company_reg_no': csv_customer['company_reg_no'],
'phone': csv_customer['phone'],
'date': csv_customer['date'],
'address': csv_customer['address']
}
}
dict_customers.append(dict_customer)
json_customers = json.dumps(dict_customers, indent=2)
print (json_customers)
r = requests.post(FRESHDESK_ENDPOINT + '/api/v2/companies',
auth=(FRESHDESK_KEY, "X"),
headers=headers,
data=json_customers,
allow_redirects=False)
只需构造所需的Python
list
或dict
,并将其传递给json.dumps
。试试这个:根据如何调用freshdesk的REST调用,您可以按原样使用}。在
dict_customers
或{测试输入:
^{pr2}$试验结果:
创建正确的JSON的懒惰方法是使用inventive查询工具,它基于公共SQL执行操作,然后只复制操作:
insert into tickets(fields) values ('a', 'b'...)
。在select * from sessionios
中执行的实际API操作。在set log-http true
将文本假脱机到文件中。在您可以通过将
csv.reader
(而不是csv.DictReader
)为每一行提供的每个数据列表转换成具有所需布局的字典,从而在文件中生成客户列表。在在下面的代码中,我使用
collections.namedtuple
,因为我认为它比使用dictionarydct['keyname']
语法生成更可读的代码。在相关问题 更多 >
编程相关推荐