當從資料庫取出的資料(特別是描述資訊)中含有特殊字元時,使用 JSON.parse 將 json 字串轉換成 json 物件就會出錯,其中雙引號、回車換行影響最為明顯,左右尖括號也會導致顯示問題。因此,在輸出到頁面進行 json 物件轉換之前,需要將這些特殊字元進行編碼或轉義。
以下展示 C# 程式碼對幾個常用特殊字元進行編碼與轉義:
theString = theString.Replace(">", ">"); theString = theString.Replace("<", "<"); theString = theString.Replace(" ", " "); theString = theString.Replace("\"", """); theString = theString.Replace("\'", "'"); theString = theString.Replace("\\", "\\\\");//對斜線的轉義 theString = theString.Replace("\n", "\\n"); theString = theString.Replace("\r", "\\r");
需要特別注意:\r 是回到行首,\n 是新啟一行,這兩者通常同時出現,應同時處理。
補充一點:文字中間的換行、空格在資料庫中並不以 \r\n、 等形式顯示出來(例如「本書」與「前80」之間的換行,「由」與「曹雪芹」之間的空格)。
文字:

資料庫:

經過測試,將這些符號編碼與轉義之後,大部分 json 字串都能順利轉換成 json 物件。若遇到個別問題,也應朝這個方向去排查。