Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

php - json_encode creating a malformed JSON (with extra hidden character)

I'm using PHP's json_encode() to return some data, retrieved by jQuery's 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);
    }
});

The PHP is:

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 by 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();

The JSON:

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

At first it seems valid. My Ajax that retrieves this PHP always ends with parseerror (thus going into the error part of ajax()).

If you copy and paste this JSON on http://jsonlint.com/, it says "Unexpected token " and http://jsonformatter.curiousconcept.com/ says is not valid.

I've tried echo json_encode($apiResponse, JSON_UNESCAPED_SLASHES); even though escaping slashes is ok / but made no difference.

But what isn't exactly valid? Wasn't PHP supposed to return valid JSON?

Extra info: Testing on Windows7, Chrome v28.XX, using PHP 5.4.XX on Apache

Questions I've read before actually posting this one:


Update:

Copying from SO into JSONlint gives valid json. So I investigated a little further and noticed the PHP is creating a weird hidden character that is actually making json invalid. See below screenshot. How I fix that? json invalid character

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It could be an issue with a BOM mark. Try to save the file as normal UTF-8 instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...