如何用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
相关产品推荐
相关产品推荐

