英文:
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(/\"/g, "\\"");
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&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&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(/"([^"]+)"/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);
输出与输入相同,第二种方法没有起作用。
我想要的只是JSON文本看起来像这样。
英文:
I using the following snippet, I'm legibly displaying all JSON strings in <pre>
tag with id="jsonText"
on the page.
var p = document.querySelectorAll("#jsonText");
var parray = [...p]
parray.forEach(p => {
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 ',' 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
.
.
.
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 <pre>
tag. (The fields are being filled by Golang's Template.)
<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>
I tried the Method 1:
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);
NOTE: The problematic field in the JSON is the "hardcore" part in the value of the "description" key.
Input:
{
"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
}
Output:
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}
I tried Method 2:
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);
The output was same as the input, at Method 2.
All I want is that the JSON text look like this.
Thanks in advance for your help.
答案1
得分: 1
由于您在使用带有Handlebars的Goland模板,如果描述字段包含引号,您提到的JSON格式将失败。您的扩展字符串:
"description": "Elon Musk says workers at the social media firm must be "hardcore" if they want to stay, reports say.",
需要进行转义:
"description": "Elon Musk says workers at the social media firm must be \"hardcore\" if they want to stay, reports say.",
我对Golang的Handlebars不太熟悉,但是假设它与常规的Handlebars兼容,您可以注册一个辅助函数来正确转义双引号,如下所示:
"description": "{{{escapeQuotes .Description}}}",
定义辅助函数以转义引号,如下所示:
Handlebars.registerHelper('escapeQuotes', function (aString) {
return aString.replace(/"/g, '\\"');
});
您可以在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:
"description": "Elon Musk says workers at the social media firm must be "hardcore" if they want to stay, reports say.",
needs to be escaped to:
"description": "Elon Musk says workers at the social media firm must be \"hardcore\" if they want to stay, reports say.",
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:
"description": "{{{escapeQuotes .Description}}}",
Define the helper function to escape quotes as follows:
Handlebars.registerHelper('escapeQuotes', function (aString) {
return aString.replace(/"/g, '\\"');
});
You can try this out at the Handlebars playground at https://handlebarsjs.com/playground.html
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论