Symael
Symael

Reputation: 35

jQuery: mysterious Json parsing error

I am getting an error on a page with a code that works perfectly on another page... Here it is:

$.each(json,function(index,element){
var tr = $("<tr>").appendTo($tabbody);
$(tr).append('<td><a target="_blank" href="forum.php?t='+element.topic_id+'">'+element.topic_nom+"</a></td>"+'<td>'+element.date_heure+"</td>");
});

json is the result of a GET request on a php page:

$data = $query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($data);

An exemple of result:

[
    {
    "topic_nom": "Deuxième question de linterro manip 5",
    "topic_id": "1",
    "user_nick": "Symael",
    "user_id": "1",
    "msg_id": "10",
    "date_heure": "2013-02-17 18:28:04"
    },
    {
    "topic_nom": "Quel est le sens de la vie ?",
    "topic_id": "2",
    "user_nick": "Symael",
    "user_id": "1",
    "msg_id": "10",
    "date_heure": "2013-02-17 18:28:04"
    }
]

Which is valid Json... The error I get is:

TypeError: invalid 'in' operand e
...ute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r...

And if I try $.parseJSON(json); :

SyntaxError: JSON.parse: unexpected character
...ute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r...

When I validate my Json on http://jsonlint.com/ the result is:

Parse error on line 1:
[    {        "to
^
Expecting '{', '['

And if a manually rewrite the first [ it suddenly becomes valid. I think I'm the victim of a very strange glitch here, could anyone help me ? Oo


Here is the solution, see Stoive's answer for explanations.

  obj = $.parseJSON(json.trim());
    $.each(obj,function(index,element){
      var tr = $("<tr>").appendTo($tabbody);
      $(tr).append('<td><a target="_blank" href="forum.php?t='+element.topic_id+'">'+element.topic_nom+"</a></td>"+'<td>'+element.date_heure+"</td>");
    });

Upvotes: 1

Views: 4545

Answers (1)

Stoive
Stoive

Reputation: 11322

Quite often, the byte order mark can sneak into files saved in editors such as Notepad.

Try fetching the character code of json at position 0 and console.log the result:

console.log(json.charCodeAt(0).toString(16));

You should be getting 5b as the result, and not something like feff. If that's the case, then JSON.parse(json.trim()) could help by removing the invisible whitespace characters.

Upvotes: 4

Related Questions