简体   繁体   中英

JSON Decode is returning the JSON string not an array or object

I am trying to pass a JSON object and use json_decode but it just wont work. The JSON is valid and the server receives it but it wont convert to an object.

To pass the JSON I am using jQuery.ajax:

    var str = jQuery('#form_data').val();
    res = str.replace("[", "");
    res = res.replace("]", "");
    form_data = JSON.stringify(res);
    console.log(form_data);

    jQuery.ajax({
        type: "POST",
        url: "/processing/test.php",
        data: form_data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
    });

To catch the JSON I am using

# Get JSON as a string
$json_str = file_get_contents('php://input');

# Get as an object
$json_obj = json_decode($json_str,true);

echo 'Last error: ', json_last_error(), PHP_EOL, PHP_EOL;
var_dump($json_obj);

json_last error returns 0

var_dump of the attemped object shows a string type.

string(208) "{"Who_Are_You":"Owner Occupier","Name":"Bob Smith","Email_Address":"removed@removed.net.au","Phone_Number":"123123","Postcode":"4164","agent":"Website Development","a_suburb":"Thornlands","formId":"40"}"

The request headers seem correct.

Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 258
Content-Type: application/json; charset=UTF-8
Cookie: removed
Host: localhost
Origin: http://localhost
Pragma: no-cache
Referer: http://localhost/removed
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36
X-Requested-With: XMLHttpRequest

When it happens, usually it's because the JSON was double encoded. The lines where you are getting form data and removing brackets might be the lines causing the issue. Try changing your javascript code to:

var form_data = JSON.stringify($('form').serializeArray())

jQuery.ajax({
    type: "POST",
    url: "/processing/test.php",
    data: form_data,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM