有没有一种方法可以从.csv创建JSON而无需导入csv?

时间:2019-07-22 17:53:36

标签: python json csv zapier

我有一些来自Google Sheets的简单的csv数据,我想使用Python将其格式化为JSON,以便可以将其发布到API。

有没有一种方法,而无需导入csv

Zapier不支持导入requests以外的任何内容。

csv数据示例:

Name,ID,Price,Qty
Row 1,123,100,1
Row 2,123,56,2
Row 3,123,90,3
Row 4,213,68,5
Row 5,765,987,789
Row 6,123,123,123

更新:这是我的位置:

Zapier screenshot

但是我得到了错误:

    File "<string>", line 11, in the_function
NameError: name 'data' is not defined

3 个答案:

答案 0 :(得分:0)

错误是因为data.csv不是有效的变量名,所以不能使用'。'。在那里。

我不知道Zapier的工作原理,但是如果您要尝试从名为“ data.csv”的文件中读取数据,并且是否想要以下格式的输出

[{"name": "Row", "ID": 1, "Price": 100, "Qty":1}, ...

然后尝试

# Reading each line the data.csv file into a list
with open("data.csv", "r") as f:
    input = f.readlines()
input = [i.strip('\n\r') for i in input] # Strip new line characters

s = "["
for k in input[1:]: # For every line except for the header
  s += '{{"Name": "{}", "ID": {}, "Price": {}, "Qty": {}}}, '.format(*k.split(","))
s += "]"

如果您尝试从变量“ input_data”(看起来像您正在尝试做的)中解析测试,请尝试。

input = input_data['data'].split("\n")

s = "["
for k in input[1:]: # For every line except for the header
  s += '{{"Name": "{}", "ID": {}, "Price": {}, "Qty": {}}}, '.format(*k.split(","))
s += "]"

答案 1 :(得分:0)

根据zapier documentation

  

仅标准Python库和请求可用。

因此import csvimport json是标准Python库,因此可以使用。

然后,这仅取决于您希望JSON输出格式为哪种格式。一个非常简单明了的转换是使用标准的Python csvjson库,如下所示:

import csv
import json

with open('data.csv') as f_input:   
    data = list(csv.DictReader(f_input))

with open('data.json', 'w') as f_output:
    json.dump(data, f_output, indent=3)

为您提供一个输出JSON文件,如下所示:

[
   {
      "Name": "Row 1",
      "ID": "123",
      "Price": "100",
      "Qty": "1"
   },
   {
      "Name": "Row 2",
      "ID": "123",
      "Price": "56",
      "Qty": "2"
   },
   {
      "Name": "Row 3",
      "ID": "123",
      "Price": "90",
      "Qty": "3"
   },
   {
      "Name": "Row 4",
      "ID": "213",
      "Price": "68",
      "Qty": "5"
   },
   {
      "Name": "Row 5",
      "ID": "765",
      "Price": "987",
      "Qty": "789"
   },
   {
      "Name": "Row 6",
      "ID": "123",
      "Price": "123",
      "Qty": "123"
   }
]

答案 2 :(得分:0)

Zapier Platform团队的David在这里。

就像其他人提到的那样,data.csv = ...不是有效的python,因此是您的错误。

为了提供一些背景信息,您的python代码设置如下:

# this is done automatically, behind the scene
s = """Name,ID,Price,Qty
Row 1,123,100,1
Row 2,123,56,2
Row 3,123,90,3
Row 4,213,68,5
Row 5,765,987,789
Row 6,123,123,123"""

input_data = {"data": s}

因此,您应该将代码解析为:

import csv

result = {}
with csv.reader(input_data['data'].splitlines()) as r:
    for line in r:
        # organize the data how you want
        pass

return result

这应该使您可以将数据转换为所需的任何形状!

您提到要将数据发送到API-您也可以在此代码步骤中执行此操作。参见HTTP examples

相关问题