我需要将数据发布到REST API。一个字段,incident_type
,需要以下面的JSON格式传递(必须包括方括号,不能只是大括号):
"incident_type_ids": [{
"name": "Phishing - General"
}],
当我试图在我的代码中强制这样做时,结果并不是很正确。通常会有一些额外的引号转义(例如输出:"incident_type_ids": "[\\"{ name : Phishing - General }\\"]"
),我意识到这是因为我在incident type
变量中对JSON数据进行了双重编码,以强制添加括号(在第6行,后来被注释掉了):
#incident variables
name = 'Incident Name 2'
description = 'This is the description'
corpID = 'id'
incident_type = '{ name : Phishing - General }'
#incident_type = json.dumps([incident_type])
incident_owner = 'Security Operations Center'
payload = {
'name':name,
'discovered_date':'0',
'owner_id':incident_owner,
'description':description,
'exposure_individual_name':corpID,
'incident_type_ids':incident_type
}
body=json.dumps(payload)
create = s.post(url, data=body, headers=headers, verify=False)
但是,由于我注释掉了这一行,我无法获得所需格式的incident_type
(带括号)。
因此,我的问题是:如何在最终的payload
中以正确的格式获取incident_type
变量
使用产品的交互式REST API手动输入:
{
"name": "Incident Name 2",
"incident_type_ids": [{
"name": "Phishing - General"
}],
"description": "This is the description",
"discovered_date": "0",
"exposure_individual_name": "id",
"owner_id": "Security Operations Center"
}
我认为我的方法是错误的,我将感谢任何帮助。我是Python的新手,所以我认为这是一个初学者的错误。
谢谢你的帮助。
发布于 2018-06-08 04:04:46
JSON方括号用于数组,对应于Python列表。JSON大括号用于对象,它对应于Python字典。
因此您需要创建一个包含字典的列表,然后将其转换为JSON。
incident_type = [{"name": "Phishing - General"}]
incident_owner = 'Security Operations Center'
payload = {
'name':name,
'discovered_date':'0',
'owner_id':incident_owner,
'description':description,
'exposure_individual_name':corpID,
'incident_type_ids':incident_type
}
body=json.dumps(payload)
与此相关的Python语法与JSON语法类似,这只是稍微巧合而已。
https://stackoverflow.com/questions/50749149
复制相似问题