1

私はページを ajax していますが、成功すると次のコードがあります。

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 に答える