Python正确的JSON格式

时间:2018-06-07 19:46:34

标签: python rest python-requests

我需要将数据发布到REST API。一个字段incident_type需要以下面的JSON格式传递(必须包括括号,不能只是大括号):

"incident_type_ids": [{
    "name": "Phishing - General"
}],

当我尝试在我的代码中强制执行此操作时,它并没有完全正确。通常会有一些额外的quote-escapes(例如输出:"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(带括号)。

所以,我的问题是:如何在最终的incident_type中以正确的格式获取payload变量?

输入我手动使用产品的交互式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的新手,所以我希望这是一个初学者的错误。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

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语法,这有点巧合。