根据输入匹配JSON中Intent示例并返回对应Dialog节点输出的实现求助
需求实现:匹配意图并返回对应对话输出
现有数据与输入
我有如下JSON结构的数据:
var jsondata = { "intents": [ { "intent": "welcome", "examples": [{ "text": "Hi" }, { "text": "Hello" } ] } ], "dialog_nodes": [{ "condition": "welcome", "output": [{ "response_type": "text", "text": "Hello" }, { "response_type": "text", "text": "How Can I help you" } ] }] }
还有一个输入字符串变量:
var input = "Hi"
需求
若输入字符串匹配intents中任意examples的text内容,获取对应的intent值;随后匹配dialog_nodes中condition与该intent值相等的节点,返回其output数组。
示例:当input = "Hi"时,应返回:
[{ "response_type": "text", "text": "Hello" }, { "response_type": "text", "text": "How Can I help you" } ]
实现代码
可以通过以下JavaScript函数实现需求:
function getMatchingOutput(jsondata, input) { // 查找匹配的intent const matchedIntent = jsondata.intents.find(intentObj => intentObj.examples.some(example => example.text === input) ); if (!matchedIntent) return []; // 查找对应dialog_node的output const matchedDialogNode = jsondata.dialog_nodes.find(node => node.condition === matchedIntent.intent ); return matchedDialogNode ? matchedDialogNode.output : []; } // 调用示例 const result = getMatchingOutput(jsondata, input); console.log(result);
代码说明
- 首先遍历
intents数组,用find结合some方法定位包含匹配输入文本的意图对象。 - 若找到匹配意图,继续遍历
dialog_nodes数组,找到condition与意图名称一致的节点,返回其output数组;未找到匹配项则返回空数组。
内容的提问来源于stack exchange,提问作者H Varma
相关产品推荐
相关产品推荐

