Iterate JSON from CSV



我需要为API创建一个从CSV中提取数据的循环。循环应在的末尾添加一个逗号{"id":BRANCH_ ID1,"具有_场景":正确}

然后对BRANCH_ID1、BRANCH_ID 2下的每一行重复相同的4行,其中有一个值,然后在最后一次迭代完成后继续到右括号。USER_ID字段将仅在每个API调用的URL中使用一次。

import http.client
import json
import csv
with open('sample.csv', 'r') as file:
reader = csv.reader(file)
next(reader)  # this is to skip the first line in the csv file
for USER_ID, BRANCH_ID in reader:
conn = http.client.HTTPSConnection("www.api.com")
payload = json.dumps({
"node_list": [
{
"id": BRANCH_ID1,
"with_descendants": True
},
{
"id": BRANCH_ID2,
"with_descendants": True
},
{
"id": BRANCH_ID3,
"with_descendants": True
}
]
})

conn.request("PUT", f"/poweruser/v1/powerusers/USER_ID/branches?access_token=0ae4f75d988900902dd9bfaa2df048e80a6fb30b", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

Sample.csv:

USER_ID,BRANCH_ID1,BRANCH_ID2,BRANCH_ID3,BRANCH_ID4,BRANCH_ID5, can keep going on as necessary
14411,332,441,446,445,110
15512,445,221,224
24412,567
23211,955,224

这将创建您的有效载荷。您可以添加回HTTP操作。使用csv模块毫无意义;您所拥有的不是合法的CSV文件,因为您有可变数量的字段。

import json
for row in open('sample.csv'):
parts = row.strip().split(',')
if parts[0] == 'USER_ID':
header = parts
else:
nodes = [{"id": int(i), "with_descendents": True} for i in parts[1:]]
payload = json.dumps( {"node_list": nodes} )
print(payload)

输出:

{"node_list": [{"id": 332, "with_descendents": true}, {"id": 441, "with_descendents": true}, {"id": 446, "with_descendents": true}, {"id": "445", "with_descendents": true}, {"id": 110, "with_descendents": true}]}
{"node_list": [{"id": 445, "with_descendents": true}, {"id": 221, "with_descendents": true}, {"id": 224, "with_descendents": true}]}
{"node_list": [{"id": 567, "with_descendents": true}]}
{"node_list": [{"id": 955, "with_descendents": true}, {"id": 224, "with_descendents": true}]}

最新更新