When formatting JSON using JavaScript I get an error because of the " (double quote) flag in the data

huangapple go评论98阅读模式
英文:

When formatting JSON using JavaScript I get an error because of the " (double quote) flag in the data

问题

我使用以下代码片段,在页面上使用<pre>标签和id="jsonText"清晰地显示所有JSON字符串。

var p = document.querySelectorAll("#jsonText");
var parray = [...p];

parray.forEach(p => {
  var data = p.textContent;
  p.textContent = JSON.stringify(JSON.parse(data), null, 2);
});

然而,当数据中有双引号(")时,我遇到了错误。

注意:JSON中有问题的字段是"value"键的值中的"hardcore"部分。

错误信息如下:

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>标签中的JSON文本(字段由Golang的模板填充):

<pre 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>

我尝试了第一种方法:

var escapedData = data.replace(/\&quot;/g, "\\&quot;");
console.log("Escaped JSON: ", escapedData);
jsonData = JSON.parse(escapedData);
p.textContent = JSON.stringify(jsonData, null, 2);
console.log("Fixed JSON: ", p.textContent);

注意:JSON中有问题的字段是"value"键的值中的"hardcore"部分。

输入:

{
"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&amp;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
}

输出:

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&amp;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}

我尝试了第二种方法:

var escapedData = data.replace(/&quot;([^&quot;]+)&quot;/g, function(match, capture) {
 return '"' + capture.replace(/&quot;/g, "\\&quot;") + '"';
});
jsonData = JSON.parse(escapedData);
p.textContent = JSON.stringify(jsonData, null, 2);
console.log("Fixed JSON: ", p.textContent);

输出与输入相同,第二种方法没有起作用。

我想要的只是JSON文本看起来像这样。

英文:

I using the following snippet, I'm legibly displaying all JSON strings in &lt;pre&gt; tag with id=&quot;jsonText&quot; on the page.

var p = document.querySelectorAll(&quot;#jsonText&quot;);

var parray = [...p]

parray.forEach(p =&gt; {
var data = p.textContent;

p.textContent = JSON.stringify(JSON.parse(data), null, 2);
});

However, I get an error when there are double quotes (") in the data.

NOTE: The problematic field in the JSON is the "hardcore" part in the value of the "description" key.

Error:

jquery.min.js:2 Uncaught SyntaxError: Expected &#39;,&#39; or &#39;}&#39; after property value in JSON at position 289
    at JSON.parse (&lt;anonymous&gt;)
    at getNews:152:33
    at Array.forEach (&lt;anonymous&gt;)
    at HTMLDocument.&lt;anonymous&gt; (getNews:143:20)
    at e (jquery.min.js:2:30005)
    at t (jquery.min.js:2:30307)
(anonymous) @ getNews:152
(anonymous) @ getNews:143
.
.
.

I tried various RegEx methods to correct the double quotes, but these methods caused insertions where escape characters should not be inserted, or they did not work at all.

This is the JSON text in &lt;pre&gt; tag. (The fields are being filled by Golang's Template.)

&lt;pre id=&quot;jsonText&quot;&gt;{&quot;guid&quot;: &quot;{{.ID}}&quot;, &quot;title&quot;: &quot;{{.Title}}&quot;, &quot;url&quot;: &quot;{{.URL}}&quot;, &quot;description&quot;: &quot;{{.Description}}&quot;, &quot;sourcename&quot;: &quot;{{.SourceName}}&quot;, &quot;sourceurl&quot;: &quot;{{.SourceURL}}&quot;, &quot;imageurl&quot;: &quot;{{.ImageURL}}&quot;, &quot;language&quot;: &quot;{{.Language}}&quot;, &quot;location&quot;: &quot;{{.Location}}&quot;, &quot;time&quot;: {{.Time}}, &quot;tags&quot;: &quot;{{.Tags}}&quot;, &quot;type&quot;: {{.Type}}}&lt;/pre&gt;

I tried the Method 1:

var escapedData = data.replace(/\&quot;/g, &quot;\\\&quot;&quot;);
console.log(&quot;Escaped JSON: &quot;, escapedData);
jsonData = JSON.parse(escapedData);
p.textContent = JSON.stringify(jsonData, null, 2);
console.log(&quot;Fixed JSON: &quot;, p.textContent);

NOTE: The problematic field in the JSON is the "hardcore" part in the value of the "description" key.

Input:

{
&quot;guid&quot;: &quot;https://www.bbc.co.uk/news/business-63648505&quot;, 
&quot;title&quot;: &quot;Elon Musk tells Twitter staff to work long hours or leave&quot;, 
&quot;url&quot;: &quot;https://www.bbc.co.uk/news/business-63648505?at_medium=RSS&amp;at_campaign=KARANGA&quot;, 
&quot;description&quot;: &quot;Elon Musk says workers at the social media firm must be &quot;hardcore&quot; if they want to stay, reports say.&quot;, 
&quot;sourcename&quot;: &quot;BBC&quot;, 
&quot;sourceurl&quot;: &quot;https://www.bbc.com/news&quot;, 
&quot;imageurl&quot;: &quot;https://www.bbc.com/news/special/2015/newsspec_10857/bbc_news_logo.png?cb=1&quot;, 
&quot;language&quot;: &quot;EN&quot;, 
&quot;location&quot;: &quot;UK&quot;, 
&quot;time&quot;: 1668616715, 
&quot;tags&quot;: &quot;&quot;, 
&quot;type&quot;: 2
}

Output:

Escaped JSON:  {\&quot;guid\&quot;: \&quot;https://www.bbc.co.uk/news/business-63648505\&quot;, \&quot;title\&quot;: \&quot;Elon Musk tells Twitter staff to work long hours or leave\&quot;, \&quot;url\&quot;: \&quot;https://www.bbc.co.uk/news/business-63648505?at_medium=RSS&amp;at_campaign=KARANGA\&quot;, \&quot;description\&quot;: \&quot;Elon Musk says workers at the social media firm must be \&quot;hardcore\&quot; if they want to stay, reports say.\&quot;, \&quot;sourcename\&quot;: \&quot;BBC\&quot;, \&quot;sourceurl\&quot;: \&quot;https://www.bbc.com/news\&quot;, \&quot;imageurl\&quot;: \&quot;https://www.bbc.com/news/special/2015/newsspec_10857/bbc_news_logo.png?cb=1\&quot;, \&quot;language\&quot;: \&quot;EN\&quot;, \&quot;location\&quot;: \&quot;UK\&quot;, \&quot;time\&quot;: 1668616715, \&quot;tags\&quot;: \&quot;\&quot;, \&quot;type\&quot;: 2}

I tried Method 2:

var escapedData = data.replace(/&quot;([^&quot;]+)&quot;/g, function(match, capture) {
 return &#39;&quot;&#39; + capture.replace(/&quot;/g, &quot;\\\&quot;&quot;) + &#39;&quot;&#39;;
});
jsonData = JSON.parse(escapedData);
p.textContent = JSON.stringify(jsonData, null, 2);
console.log(&quot;Fixed JSON: &quot;, p.textContent);

The output was same as the input, at Method 2.

All I want is that the JSON text look like this.

When formatting JSON using JavaScript I get an error because of the " (double quote) flag in the data

Thanks in advance for your help.

答案1

得分: 1

由于您在使用带有Handlebars的Goland模板,如果描述字段包含引号,您提到的JSON格式将失败。您的扩展字符串:

    &quot;description&quot;: &quot;Elon Musk says workers at the social media firm must be &quot;hardcore&quot; if they want to stay, reports say.&quot;, 

需要进行转义:

    &quot;description&quot;: &quot;Elon Musk says workers at the social media firm must be \&quot;hardcore\&quot; if they want to stay, reports say.&quot;, 

我对Golang的Handlebars不太熟悉,但是假设它与常规的Handlebars兼容,您可以注册一个辅助函数来正确转义双引号,如下所示:

    &quot;description&quot;: &quot;{{{escapeQuotes .Description}}}&quot;,

定义辅助函数以转义引号,如下所示:

Handlebars.registerHelper(&#39;escapeQuotes&#39;, function (aString) {
    return aString.replace(/&quot;/g, &#39;\\&quot;&#39;);
});

您可以在Handlebars的playground上尝试这个方法,网址是https://handlebarsjs.com/playground.html。

英文:

Since you use a Goland template with Handlebars your JSON format will fail if the Description field contains quotes, as you describe. Your expanded string:

    &quot;description&quot;: &quot;Elon Musk says workers at the social media firm must be &quot;hardcore&quot; if they want to stay, reports say.&quot;, 

needs to be escaped to:

    &quot;description&quot;: &quot;Elon Musk says workers at the social media firm must be \&quot;hardcore\&quot; if they want to stay, reports say.&quot;, 

I am not familiar with Handlebars for Golang, but assuming it is compatible with regular Handlebars you can register a helper function to properly escape double quotes for use like:

    &quot;description&quot;: &quot;{{{escapeQuotes .Description}}}&quot;,

Define the helper function to escape quotes as follows:

Handlebars.registerHelper(&#39;escapeQuotes&#39;, function (aString) {
    return aString.replace(/&quot;/g, &#39;\\&quot;&#39;);
});

You can try this out at the Handlebars playground at https://handlebarsjs.com/playground.html

huangapple
  • 本文由 发表于 2023年1月19日 18:12:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75170650.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定