如何从 JSON 的值列表中输出格式化文本?
How to output formatted text from list of values from JSON?
我正在开发一个 slackbot。我有一个 json 文件和 python 代码,可以根据用户的输入输出一些松弛的内容。有一个搜索命令可以从 json 文件中输出搜索结果。当前输出未格式化,因为当从 json 中获取值时,它们被附加到列表中,然后返回到主 python 程序。
我已经尝试创建一个循环来解析搜索输出并将其缩减,以便每组值都是独立的,然后添加到可以格式化的列表中。我试过的循环并没有真正起作用,而且我不太确定如何正确地制作一个我可以用来格式化输出的循环。我也尝试过使用 format() 格式化输出,但它不起作用,因为它是一个列表。
这是当前搜索输出的示例。
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'
这是我从另一个 python 脚本导入的示例搜索命令:
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
这是一个例子JSON:
{
"1": {
"id": "1",
"first": "Joe",
"last": "Adam"
},
"2": {
"id": "2",
"first": "Mary",
"last": "Smith"
},
"3": {
"id": "3",
"first": "Ann",
"last": "John"
}
}
我有另一个输出,我使用这行代码格式化它,我想用同样的方式格式化我的列表输出。
response = '*ID:* {}\n *First:* {}\n *Last:*
{}\n\n'.format(search['id'],search['first'],search['last'])
预期的输出是用户使用 slackbot 在 slack 中输入搜索。例如,用户可以输入 "search J",输出会列出在 "first" 或 "last" 值中具有 J 的匹配值集。我当前的输出是这样的:
[{"id":"1","first":"Joe","last":"Adam"},
{"id":"2","first":"Ann","last":"John"}]
但我想将其格式化为:
ID: 1
First: Joe
Last: Adam
ID: 2
First: Ann
Last: John
应该这样做
"\n\n".join([f"ID: {out['id']}\nFirst: {out['first']}\nLast: {out['last']}" for out in result])
我正在开发一个 slackbot。我有一个 json 文件和 python 代码,可以根据用户的输入输出一些松弛的内容。有一个搜索命令可以从 json 文件中输出搜索结果。当前输出未格式化,因为当从 json 中获取值时,它们被附加到列表中,然后返回到主 python 程序。
我已经尝试创建一个循环来解析搜索输出并将其缩减,以便每组值都是独立的,然后添加到可以格式化的列表中。我试过的循环并没有真正起作用,而且我不太确定如何正确地制作一个我可以用来格式化输出的循环。我也尝试过使用 format() 格式化输出,但它不起作用,因为它是一个列表。
这是当前搜索输出的示例。
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'
这是我从另一个 python 脚本导入的示例搜索命令:
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
这是一个例子JSON:
{
"1": {
"id": "1",
"first": "Joe",
"last": "Adam"
},
"2": {
"id": "2",
"first": "Mary",
"last": "Smith"
},
"3": {
"id": "3",
"first": "Ann",
"last": "John"
}
}
我有另一个输出,我使用这行代码格式化它,我想用同样的方式格式化我的列表输出。
response = '*ID:* {}\n *First:* {}\n *Last:*
{}\n\n'.format(search['id'],search['first'],search['last'])
预期的输出是用户使用 slackbot 在 slack 中输入搜索。例如,用户可以输入 "search J",输出会列出在 "first" 或 "last" 值中具有 J 的匹配值集。我当前的输出是这样的:
[{"id":"1","first":"Joe","last":"Adam"},
{"id":"2","first":"Ann","last":"John"}]
但我想将其格式化为:
ID: 1
First: Joe
Last: Adam
ID: 2
First: Ann
Last: John
应该这样做
"\n\n".join([f"ID: {out['id']}\nFirst: {out['first']}\nLast: {out['last']}" for out in result])