如何用Python生成符合Slack要求的嵌套Blocks消息结构?
生成符合Slack格式的嵌套字典结构
需求描述
需要用Python从两个列表生成Slack消息所需的JSON结构,每个列表元素对应一个独立的block,且每个block的text字段必须是包含type: plain_text、拼接后的文本、emoji: true的嵌套字典。给定列表:
first = ['Tomato', 'Potato', 'Fish', 'Chicken'] second = ['tasty', 'good', 'nice', 'bad']
当前问题
现有代码生成的text字段是普通字符串,不符合Slack要求的嵌套字典格式,无法正确渲染消息。现有代码如下:
dictionary = {first[i]: second[i] for i in range(len(first))} slackmessagexample = {"blocks": [ { "type": "section", "text": food + " " + taste } for food, taste in dictionary.items() ] } jsonoutput = json.dumps(slackmessagexample, indent=2) print(jsonoutput)
解决方案
只需修改列表推导式中text字段的结构,替换为嵌套字典即可。另外推荐用zip()直接配对两个列表元素,避免字典可能存在的无序问题:
import json first = ['Tomato', 'Potato', 'Fish', 'Chicken'] second = ['tasty', 'good', 'nice', 'bad'] slack_message = { "blocks": [ { "type": "section", "text": { "type": "plain_text", "text": f"{food} {taste}", "emoji": True } } for food, taste in zip(first, second) ] } json_output = json.dumps(slack_message, indent=2) print(json_output)
关键说明
- 使用
zip(first, second)按顺序配对两个列表的元素,比字典推导更可靠(Python 3.7+字典才保留插入顺序,而zip始终严格遵循列表顺序) - 将
text字段从字符串改为嵌套字典,完全匹配Slack的block格式规范 - 用f-string拼接食物名称和评价,代码更简洁易读
最终输出
运行代码后会生成符合要求的JSON结构:
{ "blocks": [ { "type": "section", "text": { "type": "plain_text", "text": "Tomato tasty", "emoji": true } }, { "type": "section", "text": { "type": "plain_text", "text": "Potato good", "emoji": true } }, { "type": "section", "text": { "type": "plain_text", "text": "Fish nice", "emoji": true } }, { "type": "section", "text": { "type": "plain_text", "text": "Chicken bad", "emoji": true } } ] }
内容的提问来源于stack exchange,提问作者Marius Vilkevičius
相关产品推荐
相关产品推荐

