从数组值中解析json

时间:2016-06-26 09:41:38

标签: python

我目前将“按钮”作为两个单独的参数传递给某个函数,如下所示:

button1 = {"title": "foo", "url": "bar" /.../ }
button2 = {"title": "foo", "url": "bar" /.../ }
somefunction(id, text, button1, button2)

def somefunction(recipient_id, message_text, button1, button2):
    data = json.dumps({
        "recipient": {
            "id": recipient_id
        },
        "message": {
            "attachment": {
                "type": "template",
                "payload": {
                    "template_type": "button",
                    "text" : message_text,
                    "buttons" : [
                        {
                            "type" : button1["type"],
                            "url" : button1["url"],
                            "title" : button1["title"]
                        },
                        {
                            "type" : button2["type"],
                            "title" : button2["title"],
                            "payload" : button2["payload"]
                        }
                    ]
                }
            }
        }
    })

如何在某些功能中重写json.dumps,以便我可以将按钮作为一个参数发送,如下所示?即如何迭代'按钮'并解析正确的json-dumps?

buttons = {
   {"title": "foo", "url": "bar" /.../ },
   {"title": "foo", "url": "bar" /.../ }
}
somefunction(id, text, buttons)

2 个答案:

答案 0 :(得分:0)

您可以发送包含'按钮列表的JSON:

somefunction

然后在{{1}}

中解析它

答案 1 :(得分:0)

您可以使用仅关键字参数(仅在使用python 3时有效)以及关键字参数解包来实现此目的:

import json
def somefunction(recipient_id, message_text, *, button1, button2):
    return json.dumps({
        "recipient": {
            "id": recipient_id
        },
        "message": {
            "attachment": {
                "type": "template",
                "payload": {
                    "template_type": "button",
                    "text" : message_text,
                    "buttons" : [
                        {
                            "type" : button1["type"],
                            "url" : button1["url"],
                            "title" : button1["title"]
                        },
                        {
                            "type" : button2["type"],
                            "title" : button2["title"],
                            "payload" : button2["payload"]
                        }
                    ]
                }
            }
        }
    })

buttons = {
    'button1' : {"title": "foo", "url": "bar", "type": "baz" },
    'button2' : {"title": "foo", "url": "bar", "type": "type2", "payload": "aLOT"}
}

x = somefunction("ID", "text", **buttons)

注意我更改了您的函数以返回json.dumps以用于我自己的调试目的。

请参阅这些构造的文档:

https://www.python.org/dev/peps/pep-3102/ https://docs.python.org/3.5/tutorial/controlflow.html#unpacking-argument-lists