在Python 3.4中,我使用Requests和for循环来组合获取JSON内容的多项API请求的主体。即使将body变量识别为带有type()的str类,它也会产生HTTP 400错误。但是,如果我将内容打印并复制到新变量中,则会成功。正在进行什么样的格式化?
import requests,json
list_length = len(namelist) #namelist arranged earlier in code
payload='['
for x in range(0, list_length):
payload += '{"name": "'+ namelist[x] + '"}'
if x<list_length-1:
payload += ', '
payload += ']'
url = 'http://api.turfgame.com/v4/users'
headers = {'Content-Type': 'application/json'}
req = requests.post(url, data=json.dumps(payload),headers=headers)
>>> payload
'[{"name": "sune"}, {"name": "Demon"}, {"name": "kingenin"}]'
答案 0 :(得分:1)
您正在创建JSON字符串,然后将其编码为JSON字符串。这种双重编码不是你想要的:
>>> payload = '[{"name": "sune"}, {"name": "Demon"}, {"name": "kingenin"}]'
>>> print(json.dumps(payload))
"[{\"name\": \"sune\"}, {\"name\": \"Demon\"}, {\"name\": \"kingenin\"}]"
这是一个JSON 字符串,包含一个引用的JSON列表..
构建列表,并将其传递给json.dumps()
:
payload = [{'name': name} for name in namelist]
url = 'http://api.turfgame.com/v4/users'
headers = {'Content-Type': 'application/json'}
req = requests.post(url, data=json.dumps(payload),headers=headers)
这会发送一个正确的JSON列表:
>>> payload
[{'name': 'sune'}, {'name': 'Demon'}, {'name': 'kingenin'}]
>>> print(json.dumps(payload))
[{"name": "sune"}, {"name": "Demon"}, {"name": "kingenin"}]
您也可以在构建时发送payload
,而不会将其传递给json.dumps()
,但为什么要让狗自己吠叫?
如果您使用requests
版本2.4.2或更高版本,您可以让它为您处理JSON编码;将 Python 对象传递到json
关键字参数中,它甚至会设置正确的Content-Type标头:
payload = [{'name': name} for name in namelist]
url = 'http://api.turfgame.com/v4/users'
req = requests.post(url, json=payload)