Python/JSON-顺序是否重要,为什么将此JSON发布到REST API失败? [英] Python/JSON - does order matter and why is this JSON post to a REST API failing?
问题描述
我要发布到Office 365 rest API,并按照以下说明创建转储:
I'm posting to the office 365 rest API and am creating the dump as per below:
def CreateEvent(auth, cal_id, subject, start_time, end_time, attendees, content):
create_url = 'https://outlook.office365.com/api/v1.0/me/calendars/{0}/events'.format(cal_id)
headers = {"Content-type": "application/json", "Accept": "application/json"}
data = {"Subject":"","Attendees": [],"End": {},"Start": {},"Body": {}}
data["Subject"] = subject
data["StartTimeZone"] = "GMT Standard Time"
data["Start"] = start_time
data["EndTimeZone"] = "GMT Standard Time"
data["End"] = end_time
data["Attendees"] = attendees
data["Body"]["ContentType"] = "Text"
data["Body"]["Content"] = content
content_data = json.dumps(data)
#return data
response = requests.post(create_url,data,headers=headers,auth=auth)
return response
这会产生无序的转储,我认为这不会引起任何问题?
This produces an unordered dump, which i believe shouldn't cause any issues?
但是,当我使用Y手动发布时,我得到201,并且创建了事件,当我使用产生以下转储的函数时,我得到了400
however, when i post manually using Y i get a 201 and the event is created, when i post using the function which produces the below dump, i get a 400
y="""
{
"Subject": "TESTTTT",
"Body": {
"ContentType": "HTML",
"Content": "I think it will meet our requirements!"
},
"Start": "2016-12-02T11:30:00Z",
"StartTimeZone": "GMT Standard Time",
"End": "2016-12-02T11:45:00Z",
"EndTimeZone": "GMT Standard Time",
"Attendees": [
{
"EmailAddress": {
"Name": "Alex ",
"Address": "alex@test.com"
},
"Type": "Required"
}
]
}
"""
我的函数返回什么并给出400
what my function returns and give a 400
{
'Body': {
'Content': 'test data',
'ContentType': 'Text'
},
'End': '2016-12-02T06:00:00Z',
'StartTimeZone': 'GMT Standard Time',
'EndTimeZone': 'GMT Standard Time',
'Start': '2016-12-02T02:00:00Z',
'Attendees': [{
'EmailAddress': {
'Name': 'Alex ',
'Address': 'alex@test.com'
},
'Type': 'Required'
}],
'Subject': 'Maintenance: test'
}
推荐答案
乍一看,我相信您只需要进行更改
At a glance, I believe you just need to change
response = requests.post(create_url,data,headers=headers,auth=auth)
到
response = requests.post(create_url,content_data,headers=headers,auth=auth)
调用json.dumps()方法序列化字典是正确的.只需将该字符串传递给服务器即可.
You were correct in calling the json.dumps() method to serialize the dictionary. Just pass that string to the server instead.
这篇关于Python/JSON-顺序是否重要,为什么将此JSON发布到REST API失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!