Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

amitsolanki24_'s avatar

ChatGPT API response to json

Hello everyone,

Im facing a problem to parse chatGPT API response to json using laravel/php.

```json\n
{\n
"classes": {\n
....
}\n```

Sometimes api returns below response

Here is your response blah blah
```json\n
{\n
"classes": {\n
....
}\n
```blah blah blah

And how can I parse some special strings or code snippet because sometimes I got null from this line json_decode($api_response);

0 likes
8 replies
jdc1898's avatar

Did you try simply cleaning the response before moving on?

$cleanJsonString = preg_replace("/\n|\r/", "", $apiResponse);
$data = json_decode($cleanJsonString, true);
1 like
amitsolanki24_'s avatar

@jdc1898 I did but sometimes its returning data with some special characters that creates problem in convert into json

RemiM's avatar

Be sure to specify your formatting preferences in the prompt.

Writting the prompt is 50% of the work.

Keep the temperature to 0, so it strictly follow your prompt.

Keep in mind that accuracy may vary depending on your model's version.

You can eventually take advantage of structured-outputs too.

Please or to participate in this conversation.