【发布时间】:2021-10-26 02:25:39
【问题描述】:
我正在尝试发出 PUT 请求,而 API 端点要求负载的结构如下:
payload_test = "[{\"id\": 1, \"channel_id\": 1, \"entity_type\": \"product\", \"entity_id\": 123, \"file_name\": \"custom-product-1.html\"}]"
我已从 CSV 文件导入值,以使用 pandas 和一些字符串操作创建类似的字符串响应。这是我打印字符串时的输出:
my_string = "[{\"id\": 1, \"channel_id\": 1, \"entity_type\": \"product\", \"entity_id\": 123, \"file_name\": \"product-custom-options.html\"}]"
我创建了my_string 以与原始有效负载请求相同,但是当我传递 my_string 时收到以下错误:请求有效负载必须是端点的 JSON 数组
当我传递payload_test 变量时,api 调用成功
这就是我创建my_string 字符串的方式:
id、channel_id 等的值是从数据帧(最初是一个 csv 文件)中获得的。
| id | channel_id | entity_type | entity_id | file_name |
|---|---|---|---|---|
| 1 | 1 | product | 123 | custom-product-1.html |
| 2 | 2 | product | 234 | custom-product-1.html |
df = pd.read_csv('xyz.csv')
for trial in df[['id', 'channel_id', 'entity_type', 'entity_id', 'file_name']].agg(pd.Series.to_json, axis='columns'):
string1 = json.dumps(trial)
my_string = string1[:1] + '[' + string1[1:-1] + ']"' #adding [ and ]" to the beginning and end
my_string = my_string.replace(':', ': ') #adding spaces after :
my_string = my_string.replace(',', ', ') #adding spaces after ,
update_template(my_string, headers)
当我打印两个字符串的类型时,它是:<class 'str'>
【问题讨论】:
标签: python json pandas string dataframe