!function(){function t(t){document.documentElement.setAttribute("data-theme",t)}var e=function(){var t=null;try{t=new URLSearchParams(window.location.search).get("docusaurus-theme")}catch(t){}return t}()||function(){var t=null;try{t=localStorage.getItem("theme")}catch(t){}return t}();t(null!==e?e:"light")}(),document.documentElement.setAttribute("data-announcement-bar-initially-dismissed",function(){try{return"true"===localStorage.getItem("docusaurus.announcement.dismiss")}catch(t){}return!1}())

[Skip to main content](#__docusaurus_skipToContent_fallback)

LangChain v0.2 is coming soon! Preview the new docs [here](/v0.2/docs/introduction/).

[

![🦜️🔗 Langchain](/v0.1/img/brand/wordmark.png)![🦜️🔗 Langchain](/v0.1/img/brand/wordmark-dark.png)

](/v0.1/)[Docs](/v0.1/docs/get_started/introduction/)[Use cases](/v0.1/docs/use_cases/)[Integrations](/v0.1/docs/integrations/platforms/)[API Reference](https://api.js.langchain.com)

[More](#)

*   [People](/v0.1/docs/people/)
*   [Community](/v0.1/docs/community/)
*   [Tutorials](/v0.1/docs/additional_resources/tutorials/)
*   [Contributing](/v0.1/docs/contributing/)

[v0.1](#)

*   [v0.2](https://js.langchain.com/v0.2/docs/introduction)
*   [v0.1](/v0.1/docs/get_started/introduction/)

[🦜🔗](#)

*   [LangSmith](https://smith.langchain.com)
*   [LangSmith Docs](https://docs.smith.langchain.com)
*   [LangChain Hub](https://smith.langchain.com/hub)
*   [LangServe](https://github.com/langchain-ai/langserve)
*   [Python Docs](https://python.langchain.com/)

[Chat](https://chatjs.langchain.com)[](https://github.com/langchain-ai/langchainjs)

Search

*   [Get started](/v0.1/docs/get_started/)
    
    *   [Introduction](/v0.1/docs/get_started/introduction/)
    *   [Installation](/v0.1/docs/get_started/installation/)
    *   [Quickstart](/v0.1/docs/get_started/quickstart/)
*   [LangChain Expression Language](/v0.1/docs/expression_language/)
    
    *   [Get started](/v0.1/docs/expression_language/get_started/)
    *   [Why use LCEL?](/v0.1/docs/expression_language/why/)
    *   [Interface](/v0.1/docs/expression_language/interface/)
    *   [Streaming](/v0.1/docs/expression_language/streaming/)
    *   [How to](/v0.1/docs/expression_language/how_to/routing/)
        
    *   [Cookbook](/v0.1/docs/expression_language/cookbook/)
        
    *   [LangChain Expression Language (LCEL)](/v0.1/docs/expression_language/)
*   [Modules](/v0.1/docs/modules/)
    
    *   [Model I/O](/v0.1/docs/modules/model_io/)
        
        *   [Quickstart](/v0.1/docs/modules/model_io/quick_start/)
        *   [Concepts](/v0.1/docs/modules/model_io/concepts/)
        *   [Prompts](/v0.1/docs/modules/model_io/prompts/)
            
        *   [LLMs](/v0.1/docs/modules/model_io/llms/)
            
        *   [Chat Models](/v0.1/docs/modules/model_io/chat/)
            
        *   [Model I/O](/v0.1/docs/modules/model_io/)
        *   [Output Parsers](/v0.1/docs/modules/model_io/output_parsers/)
            
            *   [Quick Start](/v0.1/docs/modules/model_io/output_parsers/quick_start/)
            *   [Custom output parsers](/v0.1/docs/modules/model_io/output_parsers/custom/)
            *   [Output Parser Types](/v0.1/docs/modules/model_io/output_parsers/types/)
                
                *   [String output parser](/v0.1/docs/modules/model_io/output_parsers/types/string/)
                *   [HTTP Response Output Parser](/v0.1/docs/modules/model_io/output_parsers/types/http_response/)
                *   [JSON Output Functions Parser](/v0.1/docs/modules/model_io/output_parsers/types/json_functions/)
                *   [Bytes output parser](/v0.1/docs/modules/model_io/output_parsers/types/bytes/)
                *   [Combining output parsers](/v0.1/docs/modules/model_io/output_parsers/types/combining_output_parser/)
                *   [List parser](/v0.1/docs/modules/model_io/output_parsers/types/csv/)
                *   [Custom list parser](/v0.1/docs/modules/model_io/output_parsers/types/custom_list_parser/)
                *   [Datetime parser](/v0.1/docs/modules/model_io/output_parsers/types/datetime/)
                *   [OpenAI Tools](/v0.1/docs/modules/model_io/output_parsers/types/openai_tools/)
                *   [Auto-fixing parser](/v0.1/docs/modules/model_io/output_parsers/types/output_fixing/)
                *   [Structured output parser](/v0.1/docs/modules/model_io/output_parsers/types/structured/)
                *   [XML output parser](/v0.1/docs/modules/model_io/output_parsers/types/xml/)
    *   [Retrieval](/v0.1/docs/modules/data_connection/)
        
    *   [Chains](/v0.1/docs/modules/chains/)
    *   [Agents](/v0.1/docs/modules/agents/)
        
    *   [More](/v0.1/docs/modules/memory/)
        
*   [Security](/v0.1/docs/security/)
*   [Guides](/v0.1/docs/guides/)
    
*   [Ecosystem](/v0.1/docs/ecosystem/)
    
*   [LangGraph](/v0.1/docs/langgraph/)
*   * * *
    

*   [](/v0.1/)
*   [Modules](/v0.1/docs/modules/)
*   [Model I/O](/v0.1/docs/modules/model_io/)
*   [Output Parsers](/v0.1/docs/modules/model_io/output_parsers/)
*   [Output Parser Types](/v0.1/docs/modules/model_io/output_parsers/types/)
*   JSON Output Functions Parser

On this page

JSON Output Functions Parser
============================

The JSON Output Functions Parser is a useful tool for parsing structured JSON function responses, such as those from [OpenAI functions](/v0.1/docs/modules/model_io/chat/function_calling/). This parser is particularly useful when you need to extract specific information from complex JSON responses.

Here's how it works:

1.  **Output Parser**: You can either pass in a predefined `outputParser`, or the parser will use the default `OutputFunctionsParser`.
    
2.  **Default Behavior**: If the default `OutputFunctionsParser` is used, it extracts the function call from the response generation and applies `JSON.stringify` to it.
    
3.  **argsOnly Parameter**: If the `argsOnly` parameter is set to true, the parser will only return the arguments of the function call, without applying `JSON.stringify` to the response.
    
4.  **Response Parsing**: The response from the output parser is then parsed again, and the result is returned.
    

Let's look at an example:

tip

See [this section for general instructions on installing integration packages](/v0.1/docs/get_started/installation/#installing-integration-packages).

*   npm
*   Yarn
*   pnpm

    npm install @langchain/openai

    yarn add @langchain/openai

    pnpm add @langchain/openai

    import { ChatOpenAI } from "@langchain/openai";import { JsonOutputFunctionsParser } from "langchain/output_parsers";import { HumanMessage } from "@langchain/core/messages";// Instantiate the parserconst parser = new JsonOutputFunctionsParser();// Define the function schemaconst extractionFunctionSchema = {  name: "extractor",  description: "Extracts fields from the input.",  parameters: {    type: "object",    properties: {      tone: {        type: "string",        enum: ["positive", "negative"],        description: "The overall tone of the input",      },      word_count: {        type: "number",        description: "The number of words in the input",      },      chat_response: {        type: "string",        description: "A response to the human's input",      },    },    required: ["tone", "word_count", "chat_response"],  },};// Instantiate the ChatOpenAI classconst model = new ChatOpenAI({ model: "gpt-4" });// Create a new runnable, bind the function to the model, and pipe the output through the parserconst runnable = model  .bind({    functions: [extractionFunctionSchema],    function_call: { name: "extractor" },  })  .pipe(parser);// Invoke the runnable with an inputconst result = await runnable.invoke([  new HumanMessage("What a beautiful day!"),]);console.log({ result });/**{  result: {    tone: 'positive',    word_count: 4,    chat_response: "Indeed, it's a lovely day!"  }} */

#### API Reference:

*   [ChatOpenAI](https://api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html) from `@langchain/openai`
*   [JsonOutputFunctionsParser](https://api.js.langchain.com/classes/langchain_output_parsers.JsonOutputFunctionsParser.html) from `langchain/output_parsers`
*   [HumanMessage](https://api.js.langchain.com/classes/langchain_core_messages.HumanMessage.html) from `@langchain/core/messages`

In this example, we first define a function schema and instantiate the `ChatOpenAI` class. We then create a runnable by binding the function to the model and piping the output through the `JsonOutputFunctionsParser`. When we invoke the runnable with an input, the response is already parsed thanks to the output parser.

The result will be a JSON object that contains the parsed response from the function call.

Streaming[​](#streaming "Direct link to Streaming")
---------------------------------------------------

This parser is also convenient for parsing functions responses in a streaming fashion. It supports either the aggregated functions response or a [JSON patch](https://jsonpatch.com/) diff:

    import { z } from "zod";import { zodToJsonSchema } from "zod-to-json-schema";import { ChatOpenAI } from "@langchain/openai";import { JsonOutputFunctionsParser } from "langchain/output_parsers";import { ChatPromptTemplate } from "@langchain/core/prompts";const schema = z.object({  setup: z.string().describe("The setup for the joke"),  punchline: z.string().describe("The punchline to the joke"),});const modelParams = {  functions: [    {      name: "joke",      description: "A joke",      parameters: zodToJsonSchema(schema),    },  ],  function_call: { name: "joke" },};const prompt = ChatPromptTemplate.fromTemplate(  `tell me a long joke about {foo}`);const model = new ChatOpenAI({  temperature: 0,}).bind(modelParams);const chain = prompt  .pipe(model)  .pipe(new JsonOutputFunctionsParser({ diff: true }));const stream = await chain.stream({  foo: "bears",});// Stream a diff as JSON patch operationsfor await (const chunk of stream) {  console.log(chunk);}/*  []  [ { op: 'add', path: '/setup', value: '' } ]  [ { op: 'replace', path: '/setup', value: 'Why' } ]  [ { op: 'replace', path: '/setup', value: 'Why don' } ]  [ { op: 'replace', path: '/setup', value: "Why don't" } ]  [ { op: 'replace', path: '/setup', value: "Why don't bears" } ]  [ { op: 'replace', path: '/setup', value: "Why don't bears wear" } ]  [    {      op: 'replace',      path: '/setup',      value: "Why don't bears wear shoes"    }  ]  [    {      op: 'replace',      path: '/setup',      value: "Why don't bears wear shoes?"    },    { op: 'add', path: '/punchline', value: '' }  ]  [ { op: 'replace', path: '/punchline', value: 'Because' } ]  [ { op: 'replace', path: '/punchline', value: 'Because they' } ]  [ { op: 'replace', path: '/punchline', value: 'Because they have' } ]  [    {      op: 'replace',      path: '/punchline',      value: 'Because they have bear'    }  ]  [    {      op: 'replace',      path: '/punchline',      value: 'Because they have bear feet'    }  ]  [    {      op: 'replace',      path: '/punchline',      value: 'Because they have bear feet!'    }  ]*/const chain2 = prompt.pipe(model).pipe(new JsonOutputFunctionsParser());const stream2 = await chain2.stream({  foo: "beets",});// Stream the entire aggregated JSON objectfor await (const chunk of stream2) {  console.log(chunk);}/*  {}  { setup: '' }  { setup: 'Why' }  { setup: 'Why did' }  { setup: 'Why did the' }  { setup: 'Why did the beet' }  { setup: 'Why did the beet go' }  { setup: 'Why did the beet go to' }  { setup: 'Why did the beet go to therapy' }  { setup: 'Why did the beet go to therapy?', punchline: '' }  { setup: 'Why did the beet go to therapy?', punchline: 'Because' }  { setup: 'Why did the beet go to therapy?', punchline: 'Because it' }  {    setup: 'Why did the beet go to therapy?',    punchline: 'Because it had'  }  {    setup: 'Why did the beet go to therapy?',    punchline: 'Because it had a'  }  {    setup: 'Why did the beet go to therapy?',    punchline: 'Because it had a lot'  }  {    setup: 'Why did the beet go to therapy?',    punchline: 'Because it had a lot of'  }  {    setup: 'Why did the beet go to therapy?',    punchline: 'Because it had a lot of unresolved'  }  {    setup: 'Why did the beet go to therapy?',    punchline: 'Because it had a lot of unresolved issues'  }  {    setup: 'Why did the beet go to therapy?',    punchline: 'Because it had a lot of unresolved issues!'  }*/

#### API Reference:

*   [ChatOpenAI](https://api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html) from `@langchain/openai`
*   [JsonOutputFunctionsParser](https://api.js.langchain.com/classes/langchain_output_parsers.JsonOutputFunctionsParser.html) from `langchain/output_parsers`
*   [ChatPromptTemplate](https://api.js.langchain.com/classes/langchain_core_prompts.ChatPromptTemplate.html) from `@langchain/core/prompts`

* * *

#### Help us out by providing feedback on this documentation page:

[

Previous

HTTP Response Output Parser

](/v0.1/docs/modules/model_io/output_parsers/types/http_response/)[

Next

Bytes output parser

](/v0.1/docs/modules/model_io/output_parsers/types/bytes/)

*   [Streaming](#streaming)

Community

*   [Discord](https://discord.gg/cU2adEyC7w)
*   [Twitter](https://twitter.com/LangChainAI)

GitHub

*   [Python](https://github.com/langchain-ai/langchain)
*   [JS/TS](https://github.com/langchain-ai/langchainjs)

More

*   [Homepage](https://langchain.com)
*   [Blog](https://blog.langchain.dev)

Copyright © 2024 LangChain, Inc.