Json_encode creates invalid JSON (with extra hidden character)

I use PHP json_encode() to return some data received by jQuery ajax() :

Simplified JS:

 $.ajax({ dataType: 'json', contentType: 'application/json', cache: false, type: 'POST', url: './api/_imgdown.php', error: function(jqXHR, textStatus, errorThrow) { console.log(jqXHR, textStatus, errorThrow); }, success: function(data, textStatus, jqXHR) { console.log(data, textStatus, jqXHR); } }); 

PHP:

 header('Content-Type: application/json; charset=UTF-8'); //default apiResponse $apiResponse = [ "status" => 1, "message" => "success", "data" => null ]; 

Then, when php runs my code, it ends up adding this data:

 $apiResponse['data'][] = [ "mid" => (int)$mid, "card_type" => $card_type, "header_size" => (int)$headers['Content-Length'], "saved_size" => (int)filesize($imgSavePath), "saved_path" => $imgSavePath ]; //spit out the JSON echo json_encode($apiResponse); exit(); 

JSON:

 {"status":1,"message":"success","data":[{"mid":340052,"card_type":"kakusei","header_size":48337,"saved_size":48337,"saved_path":"..\/card\/kakusei\/340052.png"}]} 

It seems right at first. My Ajax, which this PHP extracts, always ends with parseerror (thus, it enters the error part of ajax() ).

If you copy and paste this JSON to http://jsonlint.com/ , it says "Unexpected Token" and http://jsonformatter.curiousconcept.com/ says it is invalid.

I tried echo json_encode($apiResponse, JSON_UNESCAPED_SLASHES); although escape slashes are okay \/ but nothing has changed.

But what is not quite right? Wasn't PHP supposed to return valid JSON?

Additional information: testing on Windows7, Chrome v28.XX, using PHP 5.4.XX on Apache

Questions I read before posting this file:


Update:

Copying from SO to JSONlint gives valid json. So I did a little research and noticed that PHP creates a weird hidden character that actually makes json invalid. See screenshot below. How do I fix this? json invalid character

+6
source share
2 answers

This may be a problem with the specification label. Try to save the file as usual UTF-8.

+8
source

I ran into the same problem but couldn't find which file on my Windows was saved in UTF8 using the spec (even if I tried to find the files as much as I could).

However, I found a workaround. Assuming server side, I have

 die(json_encode(array( 'OK' => 1 ))) 
  • In the $ .ajax call, I delete the entry "data type:" json "and access the response with the following lines:
 success: function (response) { var data = $.parseJSON(response); console.log(data.OK); // = 1 } 
  1. In the call to $ .ajax, I still save the entry "data type:" json ", then I need to access this value inside the response, for example,

var dataOK = response ['OK']; // = 1

-1
source

Source: https://habr.com/ru/post/948544/


All Articles