最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - unable to parse json data that includes a single quote - Stack Overflow

programmeradmin1浏览0评论

Problem

I'm getting a parse error on some of my json data, because it includes single quotes. For example, some of my data could look like this:

"Larry's data"

I've read the following article: jQuery single quote in JSON response

and I've been trying to implement some of the solutions but I haven't been able to get rid of my parse error.

Code

In my model, I'm using a lua library to encode my data as json. The model returns data that looks like this:

[{\"createddatetime\":\"2013-09-10 17:56:55\",\"description\":\"John Doe\'s phone\",\"number\":\"72051\",\"createdname\":\"conversion script\",\"user\":\"23123\",\"position\":\"46\",\"id\":\"49\",\"user_id\":\"822\",\"password\":\"rwer234\"}]"

In my view, my code currently looks like this:

  $.ajax({
      url:myurl + '?startpos=' + page_index * items_per_page + '&numberofrecordstograb=' + items_per_page + '&viewtype=json',

      success: function(data){            

            console.log('inside');    
             for(var i=0;i<data.length;i++) {
                        var deviceobj = data[i];                        
                        newcontent = newcontent + "<TR>";
                        newcontent=newcontent + '<TD>';    

                        //add EDIT hyperlink
                        if ($("#editdevicesettings").val() == "true") {              
                            var temp  = $("#editlinkpath").val();
                            newcontent=newcontent +  temp.replace("xxx",deviceobj["device_id"]) + '&nbsp;&nbsp;';
                        } 

                        //add DELETE hyperlink
                        if ($("#deletedevice").val() == "true") {              
                            var temp  = $("#deletelinkpath").val();
                            newcontent=newcontent +  temp.replace("xxx",deviceobj["device_id"]);
                        }                                 
                        newcontent=newcontent + '</TD>';

                        newcontent=newcontent + '<TD>' + deviceobj["number"] +'</TD>';
                        newcontent=newcontent + '<<TD>' + deviceobj["user"] + '</TD>';
                        newcontent=newcontent + '<<TD>' + deviceobj["password"] + '</TD>';
                        if (deviceobj["name"]) {
                              newcontent=newcontent + '<TD>' + deviceobj["name"] + '</TD>';
                        } 
                        else  {
                             newcontent=newcontent + '<TD>&nbsp;</TD>';
                        }
                        newcontent=newcontent + '<TD>' + unescape(deviceobj["description"])  + '</TD>';
                        newcontent = newcontent + "</TR>";         
                }// end for 
                // Replace old content with new content
                $('#Searchresult').html(newcontent);                    
            }//end if

      },
      error: function(request, textStatus, errorThrown) {
        console.log(textStatus);
        console.log('========');
        console.log(request);

      },
      complete: function(request, textStatus) { //for additional info
        //alert(request.responseText);
        console.log(textStatus);
      }
    });

But I still get the parse error on this particular record.

Any suggestions would be appreciated. Thanks.

EDIT 1

I've changed my logic so that when it fails, it print out "request.responseText" into the console. Here's what it looks like:

"[{\"createddatetime\":\"2013-09-10 17:56:55\",\"description\":\"John Doe\'s phone\",\"number\":\"72051\",\"createdname\":\"conversion script\",\"user\":\"28567\",\"position\":\"46\",\"id\":\"49\",\"user_id\":\"822\",\"password\":\"rwer234\"}]"

The apostrophe is still escaped.

EDIT 2

Here's what my code looks like on the server side (aka. in the model):

get_device_records = function(ajaxdata)
   local results = list_devices(nil,false,ajaxdata.startpos, ajaxdata.numberofrecordstograb)
   return results.value
end

Problem

I'm getting a parse error on some of my json data, because it includes single quotes. For example, some of my data could look like this:

"Larry's data"

I've read the following article: jQuery single quote in JSON response

and I've been trying to implement some of the solutions but I haven't been able to get rid of my parse error.

Code

In my model, I'm using a lua library to encode my data as json. The model returns data that looks like this:

[{\"createddatetime\":\"2013-09-10 17:56:55\",\"description\":\"John Doe\'s phone\",\"number\":\"72051\",\"createdname\":\"conversion script\",\"user\":\"23123\",\"position\":\"46\",\"id\":\"49\",\"user_id\":\"822\",\"password\":\"rwer234\"}]"

In my view, my code currently looks like this:

  $.ajax({
      url:myurl + '?startpos=' + page_index * items_per_page + '&numberofrecordstograb=' + items_per_page + '&viewtype=json',

      success: function(data){            

            console.log('inside');    
             for(var i=0;i<data.length;i++) {
                        var deviceobj = data[i];                        
                        newcontent = newcontent + "<TR>";
                        newcontent=newcontent + '<TD>';    

                        //add EDIT hyperlink
                        if ($("#editdevicesettings").val() == "true") {              
                            var temp  = $("#editlinkpath").val();
                            newcontent=newcontent +  temp.replace("xxx",deviceobj["device_id"]) + '&nbsp;&nbsp;';
                        } 

                        //add DELETE hyperlink
                        if ($("#deletedevice").val() == "true") {              
                            var temp  = $("#deletelinkpath").val();
                            newcontent=newcontent +  temp.replace("xxx",deviceobj["device_id"]);
                        }                                 
                        newcontent=newcontent + '</TD>';

                        newcontent=newcontent + '<TD>' + deviceobj["number"] +'</TD>';
                        newcontent=newcontent + '<<TD>' + deviceobj["user"] + '</TD>';
                        newcontent=newcontent + '<<TD>' + deviceobj["password"] + '</TD>';
                        if (deviceobj["name"]) {
                              newcontent=newcontent + '<TD>' + deviceobj["name"] + '</TD>';
                        } 
                        else  {
                             newcontent=newcontent + '<TD>&nbsp;</TD>';
                        }
                        newcontent=newcontent + '<TD>' + unescape(deviceobj["description"])  + '</TD>';
                        newcontent = newcontent + "</TR>";         
                }// end for 
                // Replace old content with new content
                $('#Searchresult').html(newcontent);                    
            }//end if

      },
      error: function(request, textStatus, errorThrown) {
        console.log(textStatus);
        console.log('========');
        console.log(request);

      },
      complete: function(request, textStatus) { //for additional info
        //alert(request.responseText);
        console.log(textStatus);
      }
    });

But I still get the parse error on this particular record.

Any suggestions would be appreciated. Thanks.

EDIT 1

I've changed my logic so that when it fails, it print out "request.responseText" into the console. Here's what it looks like:

"[{\"createddatetime\":\"2013-09-10 17:56:55\",\"description\":\"John Doe\'s phone\",\"number\":\"72051\",\"createdname\":\"conversion script\",\"user\":\"28567\",\"position\":\"46\",\"id\":\"49\",\"user_id\":\"822\",\"password\":\"rwer234\"}]"

The apostrophe is still escaped.

EDIT 2

Here's what my code looks like on the server side (aka. in the model):

get_device_records = function(ajaxdata)
   local results = list_devices(nil,false,ajaxdata.startpos, ajaxdata.numberofrecordstograb)
   return results.value
end
Share Improve this question edited May 23, 2017 at 11:58 CommunityBot 11 silver badge asked Oct 10, 2013 at 18:37 dotdot 15.7k43 gold badges127 silver badges259 bronze badges 9
  • 1 I think your json data in not valid, jsonlint.com – defau1t Commented Oct 10, 2013 at 18:41
  • yeah. i've tried testing in jsonlint but all my json data fails. i don't know why. but the browser is able to parse everything... except the ones with single quotes in them. i'd like to know why my data fails in jsonlint. – dot Commented Oct 10, 2013 at 18:42
  • You have dataType: 'json' so, don't need to parse it manually, jQuery will do it, it's (data) already parsed object, also " are escaped, it's should be uncapped. – The Alpha Commented Oct 10, 2013 at 18:44
  • 1 Your example showing what the model returns is not valid at all - in real JSON, the regular double-quotes should not be escaped like that, so I'm guessing you pulled that from a debugger somewhere. Use Fiddler or your browser dev tool to watch the actual AJAX response to get the raw response. – Joe Enos Commented Oct 10, 2013 at 18:47
  • Joe Enos, I'm using Chrome's debug tools and under the Network tab, I can see all the responses I get for each ajax call. ALL my json data looks the same, and is being parsed correctly... ? I'm too new to json to know why/how it's working... but it is. The only ones that fail are the ones with the single quotes. – dot Commented Oct 10, 2013 at 18:57
 |  Show 4 more comments

4 Answers 4

Reset to default 6

Looks like you are doing double serialisation on the server side. Happens for example if your web framework automatically serialises the returned object but you make an extra explicit, unnecessary serialise call on your object. The fact that your code works with no ' cases proves this: jquery makes one parse automatically (because of the dataType) then you run another parseJSON. That shouldn't work :) Fix your serialisation on the server side and remove the unnecessary parseJSON call from your success method. Every other solution is just a workaround not a real fix.

try replacing

data = data.replace("\\'", "'");

with

data = data.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');

I had a similar problem with parsing JSON data and this code from another answer solved it

This is a bug in the lua json.encode function of the json4lua 0.9.40 library. It erroneously escapes single quotes. This is corrected in 0.9.50:

https://github.com/craigmj/json4lua

Just take out the \\ from the json response. I mean, pass the single quote as it is, like this:

[{\"createddatetime\":\"2013-09-10 17:56:55\",\"description\":\"John Doe's phone\",\"number\":\"72051\",\"createdname\":\"conversion script\",\"user\":\"23123\",\"position\":\"46\",\"id\":\"49\",\"user_id\":\"822\",\"password\":\"rwer234\"}]"
发布评论

评论列表(0)

  1. 暂无评论