首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python正确的JSON格式

Python正确的JSON格式
EN

Stack Overflow用户
提问于 2018-06-08 03:46:34
回答 1查看 345关注 0票数 0

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

代码语言:javascript
复制
"incident_type_ids": [{
    "name": "Phishing - General"
}],

当我试图在我的代码中强制这样做时,结果并不是很正确。通常会有一些额外的引号转义(例如输出:"incident_type_ids": "[\\"{ name : Phishing - General }\\"]"),我意识到这是因为我在incident type变量中对JSON数据进行了双重编码,以强制添加括号(在第6行,后来被注释掉了):

代码语言:javascript
复制
#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手动输入:

代码语言:javascript
复制
{
"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的新手,所以我认为这是一个初学者的错误。

谢谢你的帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-08 04:04:46

JSON方括号用于数组,对应于Python列表。JSON大括号用于对象,它对应于Python字典。

因此您需要创建一个包含字典的列表,然后将其转换为JSON。

代码语言:javascript
复制
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语法类似,这只是稍微巧合而已。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50749149

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档