【发布时间】:2018-11-08 13:42:16
【问题描述】:
我是 Python 新手并处理 JSON。我正在尝试从我的数据库中获取一组字符串并将它们提供给 API。我不知道为什么会出现丢失数据错误。大家可以看看吗?
###########################################
rpt_cursor = rpt_conn.cursor()
sql="""SELECT `ContactID` AS 'ContactId' FROM
`BWG_reports`.`bounce_log_dummy`;"""
rpt_cursor.execute(sql)
row_headers=[x[0] for x in rpt_cursor.description] #this will extract row headers
row_values= rpt_cursor.fetchall()
json_data=[]
for result in row_values:
json_data.append(dict(zip(row_headers,result)))
results_to_load = json.dumps(json_data)
print(results_to_load) # Prints: [{"ContactId": 9}, {"ContactId": 274556}]
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
}
targetlist = '302'
# This is for their PUT to "add multiple contacts to lists".
api_request_url = 'https://api2.xyz.com/api/list/' + str(targetlist)
+'/contactid/Api_Key/' + bwg_apikey
print(api_request_url) #Prints https://api2.xyz.com/api/list/302/contactid/Api_Key/#####
response = requests.put(api_request_url, headers=headers, data=results_to_load)
print(response) #Prints <Response [200]>
print(response.content) #Prints b'{"status":"error","Message":"ContactId is Required."}'
rpt_conn.commit()
rpt_cursor.close()
###########################################################
为清晰而编辑:
我正在传递它 [{"ContactId": 9}, {"ContactId": 274556}] 我收到了这个响应正文 b'{"status":"error","Message":"ContactId is Required."}'
API 文档将此作为请求正文的来源。 [ { “联系人 ID”:“字符串” } ]
当我手动将这些数据放入测试中时,我得到了我想要的。 [ { “联系人”:“9” }, { “联系人 ID”:“274556” } ]
也许 json.dumps 与 json.load 有什么问题?我不是在创建一个字典,而是一个看起来像字典的字符串?
编辑我想通了!:
这太愚蠢了。
在 results_to_load = json.dumps(json_data) 加载之前,我需要将 results_to_load = [] 定义为 dict。
感谢所有的回答和帮助。
【问题讨论】:
-
如果您不提供清楚的错误描述,基本上是不可能帮助您的。
-
我同意@LTClipp。这太难读了。他们是在寻找
ContactId的列表,还是只是一个列表?你给它一个清单。我建议你检查他们的 api。 -
@Ywapom 他的
json_data是一个字典列表,这似乎是合理的。并将其初始化为{}而不替换append只会给出AttributeError,并且不清楚他应该用什么替换append——你提议的 dict 中每个 subdict 的关键是什么?跨度> -
很抱歉给您带来了困惑。我的数据看起来像这样... [{"ContactId": 9}, {"ContactId": 274556}] 我收到的响应看起来像这样... b'{"status":"error ","Message":"ContactId 是必需的。"}
标签: python json python-requests