简体   繁体   English

无法解析包含单引号的json数据

[英]unable to parse json data that includes a single quote

Problem 问题

I'm getting a parse error on some of my json data, because it includes single quotes. 我在某些json数据上遇到解析错误,因为它包含单引号。 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 我已阅读以下文章: JSON响应中的jQuery单引号

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. 在我的模型中,我使用lua库将数据编码为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 编辑1

I've changed my logic so that when it fails, it print out "request.responseText" into the console. 我更改了逻辑,以使其在失败时将“ request.responseText”输出到控制台。 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 编辑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

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. 例如,如果您的Web框架自动序列化了返回的对象,但是您对对象进行了额外的显式,不必要的序列化调用,则会发生这种情况。 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. 您的代码没有大小写情况的事实证明了这一点:jquery自动进行一个解析(由于dataType),然后运行另一个parseJSON。 That shouldn't work :) Fix your serialisation on the server side and remove the unnecessary parseJSON call from your success method. 那不应该工作:)在服务器端修复序列化,并从成功方法中删除不必要的parseJSON调用。 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 我在解析JSON数据时遇到类似的问题,而另一个答案中的这段代码解决了它

This is a bug in the lua json.encode function of the json4lua 0.9.40 library. 这是json4lua 0.9.40库的lua json.encode函数中的错误。 It erroneously escapes single quotes. 错误地转义了单引号。 This is corrected in 0.9.50: 0.9.50中对此进行了更正:

https://github.com/craigmj/json4lua https://github.com/craigmj/json4lua

Just take out the \\\\ from the json response. 只需从json响应中取出\\\\。 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\"}]"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM