Hi All,
Apologies if this is a simple question, however I cannot find any documentation that can assist.
My goal here is to have severity 3 alerts in a JSON file, however I am unable to convert this list ‘alerts’ to JSON and I cannot find any documentation in the SDK v3 that could address this.
# create an instance of the API class<br/>api_instance = logicmonitor_sdk.LMApi(logicmonitor_sdk.ApiClient(configuration)) <br/>id = 138 # Integer | <br/>size = 1000 # Integer | (optional) <br/>offset = 0 # Integer | (optional) <br/>filter = f'severity:3,cleared:true,startEpoch>:{startEpoch},endEpoch<:{endEpoch}' # String | (optional)<br/><br/>#Loop shiznit<br/>alerts = []<br/>end_found = False<br/><br/>while not end_found:<br/> current = api_instance.get_alert_list_by_device_group_id(id, size=size, offset=offset, filter=filter).items<br/> alerts += current<br/> offset += len(current)<br/> end_found = len(current) != size<br/><br/>#Print and encode result to json. This allows you to use this variable later in an API Put.<br/>with open('./customer/json/cleared_sev3_alerts.json', 'w') as content_output_json:<br/> result_encoded = json.JSONEncoder(sort_keys=False, indent =4).encode(alerts)<br/> content_output_json.write(str(alerts))<br/> content_output_json.close()<br/><br/>print(len(alerts))
Whenever I try to encode this I get the following alert.
TypeError: Object of type Alert is not JSON serializable
Doing a jsonDump gives us the same output and I’ve scoured stackoverflow for a way to fix this, but no luck.
Does anyone know how I can get around this?
Thank you so much
LM User
It’s because the `alerts` list, contains a custom object of type “logicmonitor_sdk.models.alert.Alert”. It’s not a dictionary or list or other python native type that json.JSONEncoder().encode() expects. You can verify this by doing this:
So, you have to convert each item in the list to a dictionary before you can pass it to the encoder. List comprehension comes in pretty handy here. You can split it out if you want or just do it like this:
This takes advantage of the SDK’s .to_dict() method that takes LM SDK custom classes and converts them into simple dictionaries.