在 Python 中动态构建 json

Building a json dynamically in Python

我正在尝试在 Python 中构建一个 JSON。我想把它发送到 Slack。

xxdata = []
xxdata.append("Option A")
xxdata.append("Option B")
data=[]
for xx in xxdata:
    item = {"text": {
                        "type": "plain_text",
                        "text": xx,
                        "emoji": True
                    }}
    data.append(dict(item))
jsonData=json.dumps(data)

这就是我将其发送到 slack 的方式:

        {
        "type": "section",
        "block_id": "Settings1",
        "text": {
            "type": "mrkdwn",
            "text": ":gear: *MAIN*\nSelect your main group"
        },
        "accessory": {
            "type": "static_select",
            "placeholder": {
                "type": "plain_text",
                "text": "Option A",
                "emoji": True
            },
            "options": jsonData,
            "action_id": "NotificationSelect"
        }

但是,当它被发送到 Slack 时 - 我在 选项 数据前后得到额外的引号:

    {
     "type": "section", 
     "block_id": "Settings1", 
     "text": 
           {
               "type": "mrkdwn", 
               "text": ":gear: *MAIN*\nSelect your main group"}, 
     "accessory": {
               "type": "static_select",
               "placeholder": {
                       "type": "plain_text", 
                       "text": "Option A", 
                       "emoji": true}, 
     "options": "[
                 {
                  "text": 
                        {"type": "plain_text", 
                         "text": "Option A",  
                         "emoji": true}
                 },
                 {"text": 
                        {"type": "plain_text", 
                         "text": "Option B", 
                         "emoji": true}
                 }
  ]", 
       
 "action_id": "NotificationSelect"}},

这导致 Slack 失败。我究竟做错了什么? 如果我删除这些引号,一切正常。

JSON 数据包裹在 "" 中。这就是为什么 option 键的值有两个引号。

尝试跳过您执行的步骤:

jsonData=json.dumps(data)

因此,您将拥有:

xxdata = []
xxdata.append("Option A")
xxdata.append("Option B")
data=[]
for xx in xxdata:
    item = {"text": {
                        "type": "plain_text",
                        "text": xx,
                        "emoji": True
                    }}
    data.append(dict(item))

然后:

    {
    "type": "section",
    "block_id": "Settings1",
    "text": {
        "type": "mrkdwn",
        "text": ":gear: *MAIN*\nSelect your main group"
    },
    "accessory": {
        "type": "static_select",
        "placeholder": {
            "type": "plain_text",
            "text": "Option A",
            "emoji": True
        },
        "options": data,  # replace json with dict
        "action_id": "NotificationSelect"
    }

jsonData=json.dumps(data) 正在从您的列表中创建一个字符串。直接使用 data 而不是 jsonData 就可以了。