You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure Automation:如何用Python Runbook解析WEBHOOKDATA参数

How to Parse WEBHOOKDATA Parameter in Azure Automation Python Runbook

Alright, let's walk through exactly how to parse the WEBHOOKDATA parameter in your Azure Automation Python Runbook. This is a common scenario, and with a few tweaks to your initial code, you can make it robust and easy to work with:

Key Background

When you define a webhook for an Azure Automation Runbook, the incoming request's headers (and body) get packaged into a JSON string and passed to your Python script as the first command-line argument (accessible via sys.argv[1]). Your core idea of using json.loads() is spot-on—we just need to add error handling and make it easier to extract specific values.

Refined Example Code

Here's an improved version of your script that handles edge cases and clearly extracts the webhook details:

import json
import sys

def main():
    # First, check if we actually received the WEBHOOKDATA parameter
    if len(sys.argv) <= 1:
        print("No WEBHOOKDATA parameter was provided with the request.")
        return
    
    try:
        # Parse the JSON string from sys.argv[1] into a Python dictionary
        webhook_payload = json.loads(sys.argv[1])
        
        # Extract specific fields (use .get() to avoid KeyError if fields are missing)
        webhook_name = webhook_payload.get("WebhookName", "Unnamed Webhook")
        request_body = webhook_payload.get("RequestBody", "No request body provided")
        request_headers = webhook_payload.get("RequestHeader", {})
        
        # Print out the parsed information in a readable format
        print(f"=== Webhook Request Details ===")
        print(f"Webhook Name: {webhook_name}")
        print(f"Request Body: {request_body}")
        print("\nRequest Headers:")
        for header_key, header_value in request_headers.items():
            print(f"  {header_key}: {header_value}")
            
    except json.JSONDecodeError:
        print("Error: Failed to parse WEBHOOKDATA—invalid JSON format.")
    except Exception as e:
        print(f"Unexpected error occurred: {str(e)}")

if __name__ == "__main__":
    main()

What This Code Does

  • Parameter Check: Ensures we don't try to access sys.argv[1] if no parameter was sent, preventing an index error.
  • Robust Parsing: Uses try-except blocks to catch invalid JSON (a common issue if the webhook request is malformed) and other unexpected errors.
  • Safe Field Extraction: Uses .get() instead of direct key access, so if a field like WebhookName is missing, the script won't crash—it'll just use the default value you specify.
  • Readable Output: Formats the parsed data so it's easy to debug and verify what the webhook sent.

Testing with Your Example Payload

If your WEBHOOKDATA looks like this:

{"WebhookName":"python-Test-Arguments","RequestBody":"","RequestHeader":{"Cache-Control":"max-age=0","User-Agent":"Mozilla/5.0..."}}

The script will output something like:

=== Webhook Request Details ===
Webhook Name: python-Test-Arguments
Request Body: 

Request Headers:
  Cache-Control: max-age=0
  User-Agent: Mozilla/5.0...

内容的提问来源于stack exchange,提问作者Ameb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:34:49