Attempting to turn string variable with line breaks into valid JSON request

Hey guys, I have been at this for a while now and so I would really appreciate any tips.

Im trying to setup a phone number that customers can text and get an AI response using ChatGPT api. It works fine, unless the user presses the enter key, or does a line break. I get an error 400.

The reason I need this to work is because I am attempting to capture the history between this customer and chatgpt and insert it back with the new text message. But the history is stored using data store, and it has line breaks. I attempted to use replace function with no luck.

What can I type on this line so that it works properly.

Welcome to the Make community!

Escaping strings before mapping into another JSON string

Most of the time, you cannot directly map variables containing text content into another JSON string without escaping them, as the variable might contain characters that have a special meaning in JSON.

Special characters in strings needs to be specified (escaped) as a “literal” character (instead of a special metacharacter), otherwise they make the whole JSON invalid when you map the variable value when creating another JSON string.

You can escape string variables by passing the text into the JSON “Transform to JSON” module —

Transforms any object to JSON.

Then, you can map the output of the “Transform to JSON” module into your JSON string. (Do note that when using the “Transform to JSON” module, the output should already contain the double quotes " " around your text, so when you map this output into your JSON, you should not need to wrap another pair of double quotes around it.)

Alternatively, you can use the built-in function replace to replace those special characters with their escaped versions, as discussed here.

For more information on escaping JSON strings, see: Understanding JSON Escape: A Comprehensive Guide

Use the OpenAI Integration

Why aren’t you using the included OpenAI integration instead?

To do this, you can try using the OpenAI (ChatGPT, Whisper, DALL-E) “Create a Completion (Prompt) (GPT and o-series Models)” module —

Creates a completion for a prompt or chat.

For more information about the Create a Completion (Prompt) (GPT and o-series Models) module and OpenAI (ChatGPT, Whisper, DALL-E) app, see the corresponding Integrations page and the Help Centre documentation.

Hope this helps! Let me know if there are any further questions or issues. P.S.: investing some effort into the tutorials in the Make Academy will save you lots of time and frustration using Make!

@samliew