I am working on a slackbot. I have a json file and python code that outputs something to slack based on the user's input. There is a search command that outputs search results from a json file. The current output is not formatted because when the values are taken from the json, they are appended to a list and then returned to the main python program.
I have tried creating a loop that would kind of parse through the search output and cut it down so that each set of values are separate and then added to a list that can be formatted. The loop I tried doesn't really work, and I'm not too sure how to properly make a loop that I can use to format the output. I have also tried formatting the output using format(), but it doesn't work because it is a list.
This is the an example of the current search output.
if command.startswith(SEARCH):
try:
search = search_data(command.split(' ')[1])
response = search
except KeyError:
response = 'This search key does not exist.'
except TypeError:
response = 'Wrong search input'
This is an example search command that I import from another python script:
def search_data(keyword):
result = []
for key, value in data.items():
first = value['first']
last = value['last']
if keyword in first:
result.append(value)
elif keyword in last:
result.append(value)
return result
This is an example JSON:
{
"1": {
"id": "1",
"first": "Joe",
"last": "Adam"
},
"2": {
"id": "2",
"first": "Mary",
"last": "Smith"
},
"3": {
"id": "3",
"first": "Ann",
"last": "John"
}
}
I have another output which I format using this line of code and I want to format my list output the same way.
response = '*ID:* {}\n *First:* {}\n *Last:*
{}\n\n'.format(search['id'],search['first'],search['last'])
The expected output is for the user to enter a search in slack using the slackbot. The user can input "search J" for example and the output lists the matching set of values that have a J in either the "first" or "last" values. My current output is something like:
[{"id":"1","first":"Joe","last":"Adam"},
{"id":"2","first":"Ann","last":"John"}]
but I want to format it like:
ID: 1
First: Joe
Last: Adam
ID: 2
First: Ann
Last: John
this should do it
"\n\n".join([f"ID: {out['id']}\nFirst: {out['first']}\nLast: {out['last']}" for out in result])