Python标准JSON格式
我需要将数据发布到RESTAPI。一个字段,Python标准JSON格式,python,rest,python-requests,Python,Rest,Python Requests,我需要将数据发布到RESTAPI。一个字段,incident\u type,需要以下面的JSON格式传递(必须包含括号,不能只是花括号): 当我试图在代码中强制这样做时,结果并不完全正确。通常会有一些额外的引号转义(例如,输出:“事件类型”ID:“[\\”{name:Phishing-General}\\\”]”),我意识到这是因为我在事件类型变量中对JSON数据进行了双重编码,以强制添加括号(在第6行,该行已被注释掉): 但是,由于我注释掉了该行,因此无法获得所需格式(带括号)的inciden
incident\u type
,需要以下面的JSON格式传递(必须包含括号,不能只是花括号):
当我试图在代码中强制这样做时,结果并不完全正确。通常会有一些额外的引号转义(例如,输出:“事件类型”ID:“[\\”{name:Phishing-General}\\\”]”
),我意识到这是因为我在事件类型
变量中对JSON数据进行了双重编码,以强制添加括号(在第6行,该行已被注释掉):
但是,由于我注释掉了该行,因此无法获得所需格式(带括号)的incident\u 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新手,所以我认为这是初学者的错误
感谢您的帮助。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语法相似,这只是一个小小的巧合。您已经意识到必须创建一个完整的Python对象并立即将其转换为JSON。但您没有将其应用于仍然是字符串的事件类型。把它做成字典@美元。当我将其放入字典时,仍然会收到不带括号的变量:“incident_type_ids”:{“name”:“Phishing-General”}
它需要是字典列表。JSON括号=Python列表。JSON大括号=Python字典
{
"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"
}
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)