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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19303617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:37:29  来源:igfitidea点击:

unable to parse json data that includes a single quote

javascriptjqueryajaxjson

提问by dot

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:

我的一些 json 数据出现解析错误,因为它包含单引号。例如,我的一些数据可能如下所示:

"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. The model returns data that looks like this:

在我的模型中,我使用 lua 库将我的数据编码为 json。该模型返回如下所示的数据:

[{\"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. Here's what it looks like:

我已经改变了我的逻辑,以便当它失败时,它会在控制台中打印出“request.responseText”。这是它的样子:

"[{\"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

回答by peterfoldi

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.

看起来您正在服务器端进行双重序列化。例如,如果您的 Web 框架自动序列化返回的对象,但您对对象进行了额外的显式、不必要的序列化调用,则会发生这种情况。您的代码在没有 ' 情况下工作的事实证明了这一点:jquery 自动进行一个解析(因为 dataType),然后您运行另一个 parseJSON。这不应该工作:) 在服务器端修复您的序列化并从您的成功方法中删除不必要的 parseJSON 调用。所有其他解决方案都只是一种解决方法,而不是真正的解决方法。

回答by David Hariri

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 answersolved it

我在解析 JSON 数据时遇到了类似的问题,来自另一个答案的这段代码解决了这个问题

回答by Jaffadog

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:

这是json4lua 0.9.40库的lua json.encode函数中的一个bug。它错误地转义了单引号。这在 0.9.50 中得到纠正:

https://github.com/craigmj/json4lua

https://github.com/craigmj/json4lua

回答by Jacobson

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

只需从 json 响应中取出 \\ 即可。我的意思是,按原样传递单引号,如下所示:

[{\"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\"}]"