Extract JSON Node
Overview
The Extract JSON node lets you extract an object from a string containing a JSON object or array. Data outside of the JSON object or array will be ignored.
Extract JSON is very useful to extract structured data from LLM responses. Ask the LLM to reply with a JSON object, and then use Extract JSON to extract that data from its response, ignoring any text around the JSON object.
Algorithm
The node finds the first instance of {
or [
, and the last instance of }
or ]
in the string. It then extracts the substring between those two points, and attempts to parse it as JSON.
This process is not iterative at the moment, so if the parsing fails because the text contains, for example, two JSON objects, with text in between, the node will error. Use this node when you are sure that the string contains only one JSON object or array.
- Inputs
- Outputs
- Editor Settings
Inputs
Title | Data Type | Description | Default Value | Notes |
---|---|---|---|---|
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. |
Outputs
Title | Data Type | Description | Notes |
---|---|---|---|
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. |
Editor Settings
This node has no configurable editor settings.
Example 1: Extract a JSON object from an LLM response
- Create a Text Node, and ask the LLM to reply with JSON:
Please reply to this message with a JSON object.
- Create a Chat Node, and connect the Text node to its
Prompt
input. - Create an Extract JSON node, and connect the Chat node to its
Input
input. - Run the graph, and note that you see the JSON object that you replied with in the Extract JSON node's output. The
No Match
output is not ran, because there was a match.
Error Handling
This node cannot error under normal circumstances. If the input fails to extract JSON, then the No Match
output will be executed instead of the Result
output.
FAQ
Q: What if the string contains more than one JSON object?
A: The node will error. Use this node when you are sure that the string contains only one JSON object or array. For more complex use-cases, you may want to use a Code Node to parse the string in a custom way.
Q: What if I just want to call JSON.parse()
?
A: You can use a Code Node that simply calls JSON.parse() on the input string.