Micah Fletcher
Micah Fletcher

Reputation: 51

Character added to JSON string

I am using jQuery.parseJSON() to parse a response from jQuery.ajax() call to a PHP script. The code works except on some server the characters 0000 are inserted at the start of the response string causing jQuery.parseJSON() to fail.

I can not figure how those character are being inserted, any ideas? The characters are not in the PHP encoded string before echoing response.

Here is the scenario:

PHP script creates JSON string with:

$html = json_encode(myArrayOfValues);
echo $html

jQuery.ajax receives encoded string in:

....success: function(html, textStatus){
        var response = jQuery.parseJSON(html);
....

To fixed the problem I added function that removes inserted characters and changed:

var response = jQuery.parseJSON(html);

to:

var response = parseJSONResponse(html);

Where:

function parseJSONResponse(html){

    var foundChar =  html.indexOf("{");

    if(foundChar > 0 ){
        html = html.substring(foundChar);
    }

    var response = jQuery.parseJSON(html);

    return response;
}

Ultimately, it works but I'd like to know where the inserted characters are coming from and if there is a way to prevent them being inserted.

Upvotes: 1

Views: 330

Answers (1)

christurnerio
christurnerio

Reputation: 1469

This could be a character encoding related issue. \u0000 is the NULL character. Although this could just be a coincidence it seems worth looking into.

I think the preferred character encoding for json is utf-8. Try adding this to the head of your calling page and see if it resolves the issue:

<meta charset="utf-8">

Hope that helps!

Upvotes: 1

Related Questions