将字符串变量替换为http发表请求有效负载

时间:2018-06-22 09:15:52

标签: post python-requests

我正在遍历一个成分(字符串)列表的for循环,为每个元素调用http发布请求以获取其营养信息。

以下作品。

data = '{"query": "black olives"}'
r = requests.post(url, headers = headers, data = data)
body = json.loads(r.text)

但这是

for ingredient in ingredients:
    data = '{"query": ' + ingredient + '}'
    r = requests.post(url, headers = headers, data = data)
    body = json.loads(r.text)

给出错误:

{'message': 'Unexpected token r in JSON at position 10'}

我该如何解决?

编辑:现在可以使用。

1 个答案:

答案 0 :(得分:0)

从字典构造JSON更安全。

尝试一下:

import json

for ingredient in ingredients:
    data = {"query": ingredient}
    # Two options : let requests do the json conversion of the dict
    r = requests.post(url, headers = headers, json=data)
    # or do it yourself
    # r = requests.post(url, headers = headers, data=json.dumps(data))
    body = json.loads(r.text)
相关问题