
php小编新一在使用JavaScript格式化JSON时可能会遇到一个常见问题,即由于数据中的双引号标志,导致出现错误。这是因为在JavaScript中,双引号用于定义字符串,所以当数据中出现双引号时,JavaScript会将其解析为字符串的结束标志,从而导致错误。为了解决这个问题,可以使用转义字符"来转义双引号,告诉JavaScript这是一个普通的双引号而不是字符串的结束标志,从而成功格式化JSON数据。
问题内容
我使用以下代码片段,在页面上清晰地显示 <pre class="brush:php;toolbar:false;"></code> 标记中的所有 json 字符串,其中 <code>id="jsontext"</code> 。</p>
<pre class="brush:php;toolbar:false;">var p = document.queryselectorall("#jsontext");
var parray = [...p]
parray.foreach(p => {
var data = p.textcontent;
p.textcontent = json.stringify(json.parse(data), null, 2);
});</pre>
<p>但是,当数据中存在双引号 (") 时,我会收到错误。</p>
<p><strong>注意:json 中有问题的字段是“description”键值中的“hardcore”部分。</strong></p>
<p><span>立即学习</span>“<a href="https://pan.quark.cn/s/c1c2c2ed740f" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Java免费学习笔记(深入)</a>”;</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/xiazai/learn/2593" title="动态WEB网站中的PHP和MySQL:直观的QuickPro指南第2版"><img
src="https://img.php.cn/upload/webcode/000/000/000/5a2b9a88e20e5831.png" alt="动态WEB网站中的PHP和MySQL:直观的QuickPro指南第2版" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/xiazai/learn/2593" title="动态WEB网站中的PHP和MySQL:直观的QuickPro指南第2版">动态WEB网站中的PHP和MySQL:直观的QuickPro指南第2版</a>
<p>动态WEB网站中的PHP和MySQL详细反映实际程序的需求,仔细地探讨外部数据的验证(例如信用卡卡号的格式)、用户登录以及如何使用模板建立网页的标准外观。动态WEB网站中的PHP和MySQL的内容不仅仅是这些。书中还提到如何串联JavaScript与PHP让用户操作时更快、更方便。还有正确处理用户输入错误的方法,让网站看起来更专业。另外还引入大量来自PEAR外挂函数库的强大功能,对常用的、强大的包</p>
</div>
<a href="/xiazai/learn/2593" title="动态WEB网站中的PHP和MySQL:直观的QuickPro指南第2版" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div>
<p>错误:</p>
<pre class="brush:php;toolbar:false;">jquery.min.js:2 uncaught syntaxerror: expected ',' or '}' after property value in json at position 289
at json.parse (<anonymous>)
at getnews:152:33
at array.foreach (<anonymous>)
at htmldocument.<anonymous> (getnews:143:20)
at e (jquery.min.js:2:30005)
at t (jquery.min.js:2:30307)
(anonymous) @ getnews:152
(anonymous) @ getnews:143
.
.
.</pre>
<p>我尝试了各种正则表达式方法来纠正双引号,但这些方法导致插入不应插入转义字符的位置,或者根本不起作用。</p>
<p>这是 <code><pre class="brush:php;toolbar:false;"></code> 标记中的 json 文本。 (这些字段由 golang 的模板填充。)</p>
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;" id="jsontext">{"guid": "{{.id}}", "title": "{{.title}}", "url": "{{.url}}", "description": "{{.description}}", "sourcename": "{{.sourcename}}", "sourceurl": "{{.sourceurl}}", "imageurl": "{{.imageurl}}", "language": "{{.language}}", "location": "{{.location}}", "time": {{.time}}, "tags": "{{.tags}}", "type": {{.type}}}</pre>
<p>我尝试了方法1:</p>
<pre class="brush:php;toolbar:false;">var escapeddata = data.replace(/"/g, "\"");
console.log("escaped json: ", escapeddata);
jsondata = json.parse(escapeddata);
p.textcontent = json.stringify(jsondata, null, 2);
console.log("fixed json: ", p.textcontent);</pre>
<p><strong>注意:json 中有问题的字段是“description”键值中的“hardcore”部分。</strong></p>
<p><span>立即学习</span>“<a href="https://pan.quark.cn/s/c1c2c2ed740f" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Java免费学习笔记(深入)</a>”;</p>
<p>输入:</p>
<pre class="brush:php;toolbar:false;">{
"guid": "https://www.bbc.co.uk/news/business-63648505",
"title": "elon musk tells twitter staff to work long hours or leave",
"url": "https://www.bbc.co.uk/news/business-63648505?at_medium=rss&at_campaign=karanga",
"description": "elon musk says workers at the social media firm must be "hardcore" if they want to stay, reports say.",
"sourcename": "bbc",
"sourceurl": "https://www.bbc.com/news",
"imageurl": "https://www.bbc.com/news/special/2015/newsspec_10857/bbc_news_logo.png?cb=1",
"language": "en",
"location": "uk",
"time": 1668616715,
"tags": "",
"type": 2
}</pre>
<p>输出:</p>
<pre class="brush:php;toolbar:false;">escaped json: {"guid": "https://www.bbc.co.uk/news/business-63648505", "title": "elon musk tells twitter staff to work long hours or leave", "url": "https://www.bbc.co.uk/news/business-63648505?at_medium=rss&at_campaign=karanga", "description": "elon musk says workers at the social media firm must be "hardcore" if they want to stay, reports say.", "sourcename": "bbc", "sourceurl": "https://www.bbc.com/news", "imageurl": "https://www.bbc.com/news/special/2015/newsspec_10857/bbc_news_logo.png?cb=1", "language": "en", "location": "uk", "time": 1668616715, "tags": "", "type": 2}</pre>
<p>我尝试了方法2:</p>
<pre class="brush:php;toolbar:false;">var escapedData = data.replace(/"([^"]+)"/g, function(match, capture) {
return '"' + capture.replace(/"/g, "\"") + '"';
});
jsonData = JSON.parse(escapedData);
p.textContent = JSON.stringify(jsonData, null, 2);
console.log("Fixed JSON: ", p.textContent);</pre>
<p>方法 2 的输出与输入相同。</p>
<p>我想要的只是 json 文本看起来像这样。</p>
<p>预先感谢您的帮助。</p>
<h2 class="daan">解决方法</h2>
<p>由于您使用带有 handlebars 的 goland 模板,如果描述字段包含引号(如您所描述的),您的 json 格式将会失败。您的扩展字符串:</p>
<pre class="brush:php;toolbar:false;">"description": "elon musk says workers at the social media firm must be "hardcore" if they want to stay, reports say.",</pre>
<p>需要转义为:</p>
<pre class="brush:php;toolbar:false;">"description": "elon musk says workers at the social media firm must be "hardcore" if they want to stay, reports say.",</pre>
<p>我不熟悉 golang 的 handlebars,但假设它与常规 handlebars 兼容,您可以注册一个辅助函数来正确转义双引号,以便使用,例如:</p>
<pre class="brush:php;toolbar:false;">"description": "{{{escapequotes .description}}}",</pre>
<p>定义辅助函数来转义引号,如下所示:</p>
<pre class="brush:php;toolbar:false;">Handlebars.registerHelper('escapeQuotes', function (aString) {
return aString.replace(/"/g, '\"');
});</pre>
<p>您可以在 handlebars 游乐场上尝试一下,网址为 <a href="https://www.php.cn/link/fd92a703e837c873aca02bf1edfafcfe" rel="nofollow noreferrer">https://www.php.cn/link/fd92a703e837c873aca02bf1edfafcfe一个></a></p>










