18

I have the following json document

// json.json
[  
   {  
      "title":"title1",
      "value":12234
   },
   {  
      "title":"title2",
      "value":"some text"
   },
   {  
      "title":"title3",
      "value":"12qwerty234"
   },
   {  
      "title":"title4",
      "value":123.5
   }
]   

I am using jQuery to load it. Here is the code:

$(document).ready(function(){
    $.getJSON("json.json", {},function(result){
        $.each(result, function(i, obj) {
            $("form").append($('<label for="'+i+'">'+obj.title+'</label>'));
            $("form").append($('<input id="'+i+'" value="'+obj.value+'" type="text"/><br>'));
        });
    });
});

My problem is, that I am getting a syntax error in Firefox. I load json.json as a local file. Here is a screenshot (the error says "syntax error at line 1")

enter image description here

Note, that form has been generated successfully.

Edit : Here is another screenshot from Chrome when running python SimpleHTTPServer:

enter image description here

4

4 回答 4

28

The reason this happens is because you're using a local file, so a mime type of "text/xml" is implied and hence Firefox will try to parse it as XML into .responseXML of the underlying XHR object. This of course fails.

You may just ignore this, or specify the mimeType yourself:

$.ajax({
    dataType: "json",
    url: "json.json",
    mimeType: "application/json",
    success: function(result){
        $.each(result, function(i, obj) {
            $("form").append($('<label for="'+i+'">'+obj.title+'</label>'));
            $("form").append($('<input id="'+i+'" value="'+obj.value+'" type="text"/><br>'));
        });
    }
});

PS: Using plain XHR you would use overrideMimeType()

于 2013-08-17T18:34:17.250 回答
4

I ran the same code on a webserver and no syntax error is generated. While it generates a syntax error when loaded from file:///. SO, it's basically the "scheme".

于 2013-08-17T20:26:37.793 回答
1

I think, error produced because of json file is a local file. Try to load with your webserver, like nginx or apache.

于 2013-08-17T18:07:39.727 回答
0

I had faced same issue of syntax error 4 in json, while i was having correct json set.

I was unable to find the solution, then i used a trick of making json to php array. You can use the same, if you find it useful though.

Sample Code:

$json = '

{

  "title":"title4",
  "value":123.5

}';

$json = str_replace("{", "", $json); $json = str_replace("}", "", $json);

$jsonArr = explode(",", $json); $jsonArray = array();

foreach($jsonArr as $json){

    $jsonTmpArr = explode(":", $json);
    $jsonArray[trim($jsonTmpArr[0])] = trim($jsonTmpArr[1]);

}

print_r($jsonArray);

于 2018-10-15T10:19:53.280 回答