简体   繁体   中英

Python Proper JSON Format

I need to post data to a REST API. One field, incident_type , needs to be passed in the below JSON format ( must include brackets, can't be just curly brackets ):

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

When I try to force this in my code, it doesn't come out quite right. There will usually be some extra quote-escapes ( ex. output: "incident_type_ids": "[\\\\"{ name : Phishing - General }\\\\"]" )and I realized that was because I was double-encoding the JSON data in the incident type variable to forcibly add the brackets ( in line 6 which has since been commented out ):

#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)

However since I commented out the line, I can't get incident_type in the format I need ( with brackets ).

So, my question is: How can I get the incident_type variable in the proper format in the final payload ?

Input I manually got to work using product's interactive 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"
}

I figure my approach is wrong and I'd appreciate any help. I'm new to Python so I'm expecting this is a beginner's mistake.

Thanks for your help.

JSON square brackets are for arrays, which correspond to Python lists. JSON curly braces are for objects, which correspond to Python dictionaries.

So you need to create a list containing a dictionary, then convert that to 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)

It's only slightly coincidental that the Python syntax for this is similar to the JSON syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM