csv到json导入Freshdesk

时间:2016-05-09 23:00:42

标签: python json csv

这可能与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文件:

csvfile = open('FDimport.csv', 'r')
fieldnames = ('name', 'company_reg_no', 'phone', 'date', 'address')
reader = csv.DictReader(csvfile, fieldnames)
next(reader, None)

我正在努力做的是将其转换为JSON,尤其是必须将一些字段放在“custom_fields”键下。我试图建立一个列表或字典然后调用:

data=json.dumps(info)

但我无法得到正确的结构。

有什么想法吗?

由于

编辑 - 请求包含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)

3 个答案:

答案 0 :(得分:1)

创建正确的JSON的懒惰方法是使用Invantive Query Tool,它根据常见SQL执行操作,然后只复制操作:

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

答案 1 :(得分:0)

只需构建您需要的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_customersjson_customers

测试输入:

"name","company_reg_no","phone","date","address"
"Test Customer","25865","0113 12345678","2016-11-11","Some Address,
Some Road,
Some Where,
SM1 1AA"
"Test Customer 2","42","666","yesterday","123 Main St,
USA"

测试结果:

[
  {
    "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"
    }
  }
]

答案 2 :(得分:0)

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

在下面的代码中,我使用collections.namedtuple,因为我认为它比使用字典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))