Problem with json_decode - Syntax error, malformed JSON
NickName:Manu Blackwell Ask DateTime:2018-09-15T02:46:57

Problem with json_decode - Syntax error, malformed JSON

I'm receiving a json array from php as the return of curl_exec in PHP (first json PHP -> python, that returns another json), and decode fails due to bad syntax.

The piece of API code:

if($_GET['url'] == 'tomorrowdate'){
    $tomorrow = date('Y-m-d', strtotime(' + 1 days'));
    $risposta = [
        "tomorrow" => $tomorrow
    ];
    echo json_encode($risposta);
    http_response_code(200);
}

the curl code:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, array('Content-type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
//var_dump($output);
$data = stripslashes($data);
$json_array = json_decode($output, true);

//var_dump(curl_error($ch));

curl_close($ch);

var_dump($json_array);

switch (json_last_error()) {
        case JSON_ERROR_NONE:
            echo ' - No errors';
        break;
        case JSON_ERROR_DEPTH:
            echo ' - Maximum stack depth exceeded';
        break;
        case JSON_ERROR_STATE_MISMATCH:
            echo ' - Underflow or the modes mismatch';
        break;
        case JSON_ERROR_CTRL_CHAR:
            echo ' - Unexpected control character found';
        break;
        case JSON_ERROR_SYNTAX:
            echo ' - Syntax error, malformed JSON';
        break;
        case JSON_ERROR_UTF8:
            echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
        break;
        default:
            echo ' - Unknown error';
        break;
    }

I tried to adapt your code with mine but the problem remains ...

function remove_utf8_bom($text){
    $bom = pack('H*','EFBBBF');
    $text = preg_replace("/^$bom/", '', $text);
    return $text;
}
$tomorrow = date('Y-m-d', strtotime(' + 1 days'));
$risposta = [
            "tomorrow" => $tomorrow
           ];
$json = remove_utf8_bom($risposta);
echo json_encode($json);
var_dump(json_decode($json_encode, TRUE));

The output is:

{"tomorrow":"2018-09-15"}NULL - Syntax error, malformed JSON

Copyright Notice:Content Author:「Manu Blackwell」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/52337698/problem-with-json-decode-syntax-error-malformed-json

Answers
Jay Blanchard 2018-09-14T19:14:58

Using the following code I can see there is a non-printable character at the beginning of the JSON:\n$json = '{"tomorrow":"2018-09-15"}';\nvar_dump(json_encode($json));\n\nReturns:\nstring(37) ""\\ufeff{\\"tomorrow\\":\\"2018-09-15\\"}""\n\nThe string ufeff is a BOM. To remove it use the following function:\nfunction remove_utf8_bom($text){\n $bom = pack('H*','EFBBBF');\n $text = preg_replace("/^$bom/", '', $text);\n return $text;\n}\n\nwhich returns:\nstring(31) ""{\\"tomorrow\\":\\"2018-09-15\\"}""\n\nNow using all of the code:\nfunction remove_utf8_bom($text)\n{\n $bom = pack('H*','EFBBBF');\n $text = preg_replace("/^$bom/", '', $text);\n return $text;\n}\n$json = remove_utf8_bom('{"tomorrow":"2018-09-15"}');\nvar_dump(json_encode($json));\nprint_r(json_decode($json, TRUE));\n\nWhich returns:\nstring(31) ""{\\"tomorrow\\":\\"2018-09-15\\"}""\nArray\n(\n [tomorrow] => 2018-09-15\n)\n\n##EDIT based on comments:\nChange the last the lines of your code:\n$json = remove_utf8_bom(json_encode($risposta)); // encode here\n//echo json_encode($json); // don't really need this, just a test\nvar_dump(json_decode($json, TRUE)); // you had $json_encode here\n\nThis returns EXAMPLE:\narray(1) {\n ["tomorrow"]=>\n string(10) "2018-09-15"\n}\n",


More about “Problem with json_decode - Syntax error, malformed JSON” related questions

Problem with json_decode - Syntax error, malformed JSON

I'm receiving a json array from php as the return of curl_exec in PHP (first json PHP -> python, that returns another json), and decode fails due to bad syntax. The piece of API code: if($_GET['u...

Show Detail

I got this error Syntax error, malformed JSON

Im integrating Lightspeed API to my website like POS system. I currently getting the value file_get_contents(), but when Im trying to load it array I gives my the error 4 of json_last_error(). Her...

Show Detail

PHP json_decode JSON_ERROR_SYNTAX

I try to load and parse JSON file from this link But I have JSON_ERROR_SYNTAX problem and Invalid argument supplied for foreach(). Why it's happen? [{ "Manufacturer": "Toyota", "Sold": 1200, "Mon..

Show Detail

drupal api returns json causes syntax error, malformed JSON in json_decode function of php

In my drupal website, I use drupal web service module to provide api for android and php clients. This is my sample api link (http://localhost/myproject/api/v1/users/registered_users/retrieve.json)...

Show Detail

json_decode and StackExchange api

I'm trying to use the V2.2 of StackExchange api with PHP. I'm using the Symfony project with Kriswallsmith's buzz library. The problem comes when I try to print the content of response of HTTP req...

Show Detail

json_decode return "JSON_ERROR_SYNTAX", however JSON seems OK

What is wrong with this JSON string in PHP? [{"Type":"Chasse|Loisirs","Productions":"Bois d\'Œuvre|Bois de chauffage","Essences principales > Feuillus":"Bouleaux|Hêtres

Show Detail

Syntax error, malformed JSON SLIMCD

When request for Transaction using Slimcd. I have issue "Syntax error, malformed JSON ". I have searched through google nothing found useful. // Create a ProcessTransaction Request class $request ...

Show Detail

JSON syntax error occure when jsone_decode in php but json data actually not contain any syntax error

I am trying to get post details using JSON in wordpress. In my plugin following is the json_decode part. But it returns null. $post_count = intval($instance['post_count']); $eng_posts= @json_decode(

Show Detail

json_decode - malformed JSON from AJAX Request

I am building a request in Flash that contains a JSON encoded Array of Objects. This is encoded using as3corelib. The request is then passed to JavaScript via ExternalInterface and a jquery ajax call

Show Detail

PHP json_decode returns null on valid string

I have the following code: $option = $this->request->post['option']; var_dump($option); echo "<br>"; var_dump(json_decode($option)); The dumps show: string(118) &q

Show Detail