Home > other >  Removing Last Comma in JSON
Removing Last Comma in JSON

Time:09-29

I tried the previous solutions here but my problem still persists.

When I make json_decode($result) the response I get with cURL, I get "NULL".

When I do var_dump($response), the string type response is as follows.

As far as I understand, this problem occurs because of the comma in the last part.

My response (in string type):

{
  "returnCode": "0",
  "returnMessage": "bla bla bla message",
  "fast": "H",
}

CodePudding user response:

A str_replace could work here:

$cleaned_response = str_replace($response, ",\n}", "}");

You just need to make sure you get the newline character right.

CodePudding user response:

You can use json_last_error() to find about the eventual eror when using json_decode().

But no matter what, you are right : the response you get is not a valid JSON, it must not have this last comma.

Example here : http://sandbox.onlinephpfunctions.com/code/21c25760f21c5d33dc7f0c6397161fa4a26b3b81

  • Related