1

我正在 ajaxing 一个页面,成功后我有以下代码:

success: function(html){
var product_json = [];
data=$(html);

$(".product_json", data).each(function(){
      product_json.push( jQuery.parseJSON( $(this).html() ) );
});
....
//code continue 

我的 Json 看起来像:

{
  "item_logoagenzia": "/resource/loghi/medium/13.gif",
  "item_description": "Some Bernini ven.."
}

如果我有一些像双引号这样的字符它停止工作,它工作正常。

错误 Json 看起来像:

 {
  "item_logoagenzia": "/resource/loghi/medium/13.gif",
  "item_description": "Some "Bernini" ven.."
}

我无法控制 json 创建。如何修改它或删除上面给出的脚本中的双引号等特殊字符?

4

2 回答 2

1

我已经做了。我修改了我的代码:

$(".product_json", data).each(function(){
  product_json.push( jQuery.parseJSON( $(this).html() ) );
});

$(".product_json", data).each(function(){
var myString = $(this).html().split('"item_description":"');

var myStringDesc = myString[1]; //split the string into two

myStringDesc = myStringDesc.substring(0, myStringDesc.length - 2);

myStringDesc = escapeHtml(myStringDesc);//escapeHtml is just function for removing special chars

var myNewString = eval( '('+ myString[0]+'"item_description":"'+ myStringDesc+'"}'+')');

myNewString = JSON.stringify(myNewString);

product_json.push( jQuery.parseJSON( myNewString ) );
 });

我不确定代码的效率,但它看起来工作正常。

于 2012-07-27T18:35:49.187 回答
-3

你的 JSON 应该是:

{
  "item_logoagenzia": "/resource/loghi/medium/13.gif",
  "item_description": "Some \"Bernini\" ven.."
}

编辑:好的,我没有看到作者不能编辑 JSON ......

你可以试试:

$(this).html().replace("\"Bernini\"","\\\"Bernini\\\"")

但这取决于您收到的 html

success: function(html){
var product_json = [];
data=$(html);

$(".product_json", data).each(function(){
      product_json.push( jQuery.parseJSON( $(this).html().replace("\"Bernini\"","\\\"Bernini\\\"") ) );
});

另一个可能有效的解决方案是,您可以删除/替换值中的所有双引号,第一个和最后一个引号除外....这样您将收到有效的 JSON 字符串,但您将显示不带引号的描述,否则它将是带单引号。

于 2012-07-26T13:34:09.063 回答