Khoa Nguyen Khoa Nguyen - 1 month ago 5
JSON Question

How to return array list as a python object?

I have a method which sends message to facebook in Generic template .
My code:

def send_receipt(self, fbid, title, url, img_url, summary):
return self._send(message={
"recipient": {
"id": fbid
},
"message": {
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"elements": [
{
"title": title,
"item_url": url,
"image_url": img_url,
"subtitle": summary
}
]
}
}
}
})


It works fine for me, but it only returns 1 element. I want to get 2 or 3 elements from JSON, so I think that I can make it works by making an element object and this object returns the array list.

def send_receipt(self, fbid, elements):
return self._send(message={
"recipient": {
"id": fbid
},
"message": {
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"elements": elements
}
}
}
})


And I did make a method to return elements. But i'm new to python, so what I have done didnt work for me.

elements = [{
"title": title,
"item_url": url,
"image_url": img_url,
"subtitle": summary }]

Answer

What I do is making a method which converts the result to a list elements

temp = []
for index, product in enumerate(products):
    element = {'title': title,
               'subtitle': sumary,
               'item_url': item_url}
    #not every product has image_url so to prevent KeyError, I have a if
    if 'image_url' in product:
        element['image_url'] = image_url
    temp.append(element)
    # In Facebook API element is limited to 10
    if index == 9:
       break
return temp
Comments