要导入到csv的Freshdes

2024-06-16 09:09:18 发布

您现在位置:Python中文网/ 问答频道 /正文

这可能与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)

Tags: csvnojsonfieldsdateaddresscustomphone
3条回答

只需构造所需的Python listdict,并将其传递给json.dumps。试试这个:

import csv
import 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)

根据如何调用freshdesk的REST调用,您可以按原样使用dict_customers或{}。在

测试输入:

^{pr2}$

试验结果:

[
  {
    "name": "Test Customer", 
    "custom_fields": {
      "date": "2016-11-11", 
      "phone": "0113 12345678", 
      "company_reg_no": "25865", 
      "address": "Some Address,\nSome Road,\nSome Where,\nSM1 1AA"
    }
  }, 
  {
    "name": "Test Customer 2", 
    "custom_fields": {
      "date": "yesterday", 
      "phone": "666", 
      "company_reg_no": "42", 
      "address": "123 Main St,\nUSA"
    }
  }
]

创建正确的JSON的懒惰方法是使用inventive查询工具,它基于公共SQL执行操作,然后只复制操作:

  • 执行insert into tickets(fields) values ('a', 'b'...)。在
  • 复制在select * from sessionios中执行的实际API操作。在
  • 可选地使用set log-http true将文本假脱机到文件中。在

您可以通过将csv.reader(而不是csv.DictReader)为每一行提供的每个数据列表转换成具有所需布局的字典,从而在文件中生成客户列表。在

在下面的代码中,我使用collections.namedtuple,因为我认为它比使用dictionary dct['keyname']语法生成更可读的代码。在

from collections import namedtuple
import csv
import json
try:
    from itertools import imap
except ImportError:  # Python 3
    imap = map

with open('FDimport.csv', 'rb') as csvfile:
    FIELD_NAMES = 'name', 'company_reg_no', 'phone', 'date', 'address'
    Customer = namedtuple('Customer', FIELD_NAMES)
    reader = csv.reader(csvfile, FIELD_NAMES)
    info = [dict(name=customer.name,
                 custom_fields=dict(
                     company_reg_no=customer.company_reg_no,
                     phone=customer.phone,
                     date=customer.date,
                     address=customer.address))
            for customer in imap(Customer._make, reader)]

print(json.dumps(info, indent=4))

相关问题 更多 >