Python正确的JSON格式

2024-04-23 05:30:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要将数据发布到restapi。一个字段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新手,所以我认为这是初学者的错误。你知道吗

谢谢你的帮助。你知道吗


Tags: 数据nameidjsonids格式typedescription
1条回答
网友
1楼 · 发布于 2024-04-23 05:30:17

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语法相似。你知道吗

相关问题 更多 >