如何解决JSONPLACEHOLDER:如何为每个字典发布具有唯一“ id”的字典列表?
我有下面的词典列表:
lst = [{'userId': 123,'title': 'John','body': 'Developer'},{'userId': 2,'title': 'James','body': 'QA'},{'userId': 32,'title': 'Peter','body': 'BA'},{'userId': 12,'title': 'Andrew','body': 'Project Manager'},{'userId': 111,'title': 'Alisha','body': 'Team Lead'}]
我试图将这些虚假数据发布到虚假服务器:
https://jsonplaceholder.typicode.com/posts
列表中的每本词典都有不同的“ id”。
这是我的代码:
import sys
import json
import requests
lst = [{'userId': 123,'body': 'Team Lead'}]
endpoint = "https://jsonplaceholder.typicode.com/posts/"
header = {"Content-type": "application/json"}
for i in lst:
send_data = i
try:
response = requests.post(endpoint,json=send_data,headers=header)
if response.status_code not in (200,201,202):
raise Exception("Non-successful HTTP request")
posted_data = json.loads(response.content.decode("utf-8"))
print(json.dumps(posted_data,indent=4,sort_keys=True))
data_id = posted_data['id']
print(f"Added post with id {data_id}")
except Exception as x:
sys.stderr.write(str(x))
sys.exit(2)
这是输出:
{
"body": "Developer","id": 101,"title": "John","userId": 123
}
Added post with id 101
{
"body": "QA","title": "James","userId": 2
}
Added post with id 101
{
"body": "BA","title": "Peter","userId": 32
}
Added post with id 101
{
"body": "Project Manager","title": "Andrew","userId": 12
}
Added post with id 101
{
"body": "Team Lead","title": "Alisha","userId": 111
}
Added post with id 101
如您所见,它以相同的“ id”发布数据,但我需要为每个字典以不同的“ id”发布数据。
我该怎么做?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。