JSON插入HTML报‘unexpected end of string’错误的解决方法
在JSON中嵌入HTML的正确方法及错误修复方案
你遇到的"unexpected end of string"错误,核心问题不是双引号转义,而是JSON字符串不允许包含未转义的换行符——你的HTML代码里有大量换行,这才是触发报错的原因。
正确的处理方式有两种:
- 压缩HTML为单行:把HTML里所有的换行、多余空格都删掉,整合成一行字符串,同时确保所有双引号都用
\转义(你已经做了这步)。 - 转义换行符:保留HTML的格式,但把每一处实际的换行替换成
\n,这样JSON解析器就能识别。
修复后的代码示例(以压缩单行为例):
{ "splash": { "splashContent": "<div style=\"text-align: justify;\"><h2><b><u><span style=\"color:windowtext;mso-ansi-language:EN-US\">Theoretical background:<o:p></o:p></span></u></b></h2><h2><span style=\"font-weight: normal;\"><font size=\"3\"><span style=\"mso-ansi-language:EN-US\">In this area of the application, you can find a comparison between the predicted air pollutant concentration values of the CITYCHEM model’s forecast and real measurement data from the city of Hamburg.</span></font></span></h2><h2><span style=\"font-weight: normal;\"><font size=\"3\"><span style=\"mso-ansi-language:EN-US\"><br /> </span><span style=\"mso-ansi-language:EN-US\">There are fifteen active measurement stations located in Hamburg, which measure O<sub>3</sub>, PM10, NO<sub>2</sub> and <span style=\"color:black;mso-themecolor:text1\">NO. </span></span><span style=\"mso-ascii-font-family:Calibri;mso-hansi-font-family:Calibri;mso-bidi-font-family: Calibri;color:black;mso-themecolor:text1;mso-ansi-language:EN-US\">For PM10, the hourly forecast data is compared to measured daily running mean values. </span></font></span><span style=\"mso-ansi-language:EN-US\"><font size=\"3\" style=\"font-weight: normal;\">Other pollutants like SO<sub style=\"\">2</sub> or CO are not included in this validation as they are constantly below threshold values. The measurement data can be accessed freely from the ‘Hamburg Luftmessnetz.</font></span></h2></div>", "requireConfirm": false, "confirm": { "text": "", "color": "#ffffff", "transparency": 0 }, "showOption": false, "confirmEverytime": true, "contentVertical": "top", "size": { "mode": "wh", "wh": { "w": 1500, "h": 900 } }, "background": { "mode": "color", "image": null, "type": "fill", "fileName": "No%20file%20chosen", "color": "#ffffff", "transparency": 0 }, "button": { "color": "#518dca", "transparency": 0, "text": "OK" } } }
额外提示
如果手动处理麻烦,可以用在线JSON转义工具,把HTML片段粘贴进去,工具会自动帮你完成所有必要的转义(包括换行和双引号),直接复制结果到JSON里就行。
内容的提问来源于stack exchange,提问作者Rehan
相关产品推荐
相关产品推荐

