如何在给定此脚本的情况下一次提取多个JSON密钥 - 该脚本循环显示消息ID列表并提取JSON响应。我只想从响应中提取某些键。
import urllib3
import json
import csv
from progressbar import ProgressBar
import time
pbar = ProgressBar()
base_url = 'https://api.pipedrive.com/v1/mailbox/mailMessages/'
fields = {"include_body": "1", "api_token": "token"}
json_arr = []
http = urllib3.PoolManager()
with open('ten.csv', newline='') as csvfile:
for x in pbar(csv.reader(csvfile, delimiter=' ', quotechar='|')):
r = http.request('GET', base_url + "".join(x), fields=fields)
mails = json.loads(r.data.decode('utf-8'))
json_arr.append(mails['data']['from'][0]['id'])
print(json_arr)
这是按预期工作的。但我想做以下事情。
json_arr.append(mails(['data']['from'][0]['id'],['data']['to'][0]['id'])
导致TypeError:list indices必须是整数或切片,而不是str
答案 0 :(得分:2)
你的意思是:
json_arr.append(mails['data']['from'][0]['id'])
json_arr.append(mails['data']['to'][0]['id'])
答案 1 :(得分:0)
已发布的答案看起来不错,但我会使用extend()
代替append()
分享单行代码:
json_arr.extend([mails['data']['from'][0]['id'], mails['data']['to'][0]['id']])