You need to enable JavaScript to run this app. 如何用Python解析Azure Queue Storage中嵌套的EventGrid消息?
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python解析Azure Queue Storage中嵌套的EventGrid消息?

问题解决方法

核心原因

你当前无法直接访问字段的问题出在:使用json.dumps()方法把包含解析后body的字典序列化成了JSON字符串,字符串类型不支持通过键名['body']['data']['blobUrl']的方式访问嵌套内容。你需要先将所有层级的JSON内容解析为Python字典,再进行字段访问。

实现代码

import logging
import json

import azure.functions as func

def main(msg: func.QueueMessage):
    logging.info('Python queue trigger function processed a queue item.')
    
    # 解析队列消息中嵌套的Event Grid消息
    raw_msg_body = msg.get_body().decode('utf-8')
    event_grid_data = json.loads(raw_msg_body)
    
    # 构造存储消息全量信息的Python字典(不要提前序列化为字符串)
    full_msg = {
        'id': msg.id,
        'body': event_grid_data,
        'expiration_time': msg.expiration_time.isoformat() if msg.expiration_time else None,
        'insertion_time': msg.insertion_time.isoformat() if msg.insertion_time else None,
        'time_next_visible': msg.time_next_visible.isoformat() if msg.time_next_visible else None,
        'pop_receipt': msg.pop_receipt,
        'dequeue_count': msg.dequeue_count
    }
    
    # 仅在需要输出日志时,将字典序列化为JSON字符串
    logging.info(json.dumps(full_msg))
    
    # 直接通过字典键访问你需要的字段
    target_blob_url = full_msg['body']['data']['blobUrl']
    logging.info(f"提取到的Blob访问地址:{target_blob_url}")

额外说明

Azure Functions的Queue Trigger返回的QueueMessage对象没有内置的get_json()方法,必须手动执行「字节解码→JSON反序列化」两步操作完成嵌套消息的解析。如果需要操作字段,始终优先操作原生Python字典,json.dumps()仅在需要打印日志、传输数据等需要字符串格式的场景下使用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 09:18:03