提取JSON节点
概述
Extract JSON节点允许您从包含JSON对象或数组的字符串中提取对象。JSON对象或数组之外的数据将被忽略。
Extract JSON 功能非常有用,可以从LLM响应中提取结构化数据。要求LLM以JSON对象形式回复,然后使用Extract JSON从其响应中提取该数据,忽略JSON对象周围的任何文本。
算法
该节点会查找字符串中第一个出现的{
或[
,以及最后一个出现的}
或]
。然后提取这两个点之间的子字符串,并尝试将其解析为JSON。
目前这个过程不是迭代的,因此如果解析失败(例如文本中包含两个JSON对象且中间有文本),节点将会报错。当您确定字符串仅包含一个JSON对象或数组时,请使用此节点。
- 输入
- 输出
- 编辑器设置
输入项
标题 | 数据类型 | 描述 | 默认值 | 备注 |
---|---|---|---|---|
Input | string | The string that a JSON object or array will be extracted from. | (required) | The input will be coerced into a string if it is not a string. |
输出
标题 | 数据类型 | 描述 | 备注 |
---|---|---|---|
Output | object | The string or array that was extracted from the string. | If there was no string or array found in the input string, then this port will not be ran. |
No Match | string | If there was no string or object found in the input text, then this port will run, with the full contents of the input string. | If there was a string or array found in the input string, this port will not be ran. |
编辑器设置
该节点没有可配置的编辑器设置。
示例1:从LLM响应中提取JSON对象
- 创建一个文本节点,并要求LLM以JSON格式回复:
请以JSON对象的形式回复此消息。
- 创建一个Chat Node,并将Text节点连接到它的
Prompt
输入。 - 创建一个Extract JSON节点,并将Chat节点连接到它的
Input
输入端口。 - 运行图形,并注意您会在Extract JSON节点的输出中看到回复的JSON对象。
No Match
输出未运行,因为存在匹配项。
错误处理
该节点在正常情况下不会出错。如果输入内容无法提取JSON,则将执行No Match
输出而非Result
输出。
常见问题
问:如果字符串包含多个JSON对象怎么办?
A: 节点会报错。当您确定字符串仅包含一个JSON对象或数组时使用此节点。对于更复杂的用例,您可能需要使用Code Node以自定义方式解析字符串。
问:如果我只想调用JSON.parse()
怎么办?
A: 你可以使用一个Code Node,它只需在输入字符串上调用JSON.parse()。