Table of Contents
问题内容
解决方法
Home Backend Development Golang When formatting JSON using JavaScript, I get an error due to the '(double quote) flag in the data

When formatting JSON using JavaScript, I get an error due to the '(double quote) flag in the data

Feb 09, 2024 pm 04:10 PM

使用 JavaScript 格式化 JSON 时,由于数据中的“(双引号)标志,我收到错误

php小编新一在使用JavaScript格式化JSON时可能会遇到一个常见问题,即由于数据中的双引号标志,导致出现错误。这是因为在JavaScript中,双引号用于定义字符串,所以当数据中出现双引号时,JavaScript会将其解析为字符串的结束标志,从而导致错误。为了解决这个问题,可以使用转义字符\"来转义双引号,告诉JavaScript这是一个普通的双引号而不是字符串的结束标志,从而成功格式化JSON数据。

问题内容

我使用以下代码片段,在页面上清晰地显示

</code> 标记中的所有 json 字符串,其中 <code>id="jsontext"</code> 。</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><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);
});
Copy after login

但是,当数据中存在双引号 (") 时,我会收到错误。

注意:json 中有问题的字段是“description”键值中的“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
.
.
.
Copy after login

我尝试了各种正则表达式方法来纠正双引号,但这些方法导致插入不应插入转义字符的位置,或者根本不起作用。

这是

</code> 标记中的 json 文本。 (这些字段由 golang 的模板填充。)</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'><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}}}
Copy after login

我尝试了方法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);
Copy after login

注意:json 中有问题的字段是“description”键值中的“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
}
Copy after login

输出:

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}
Copy after login

我尝试了方法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);
Copy after login

方法 2 的输出与输入相同。

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

预先感谢您的帮助。

解决方法

由于您使用带有 handlebars 的 goland 模板,如果描述字段包含引号(如您所描述的),您的 json 格式将会失败。您的扩展字符串:

"description": "elon musk says workers at the social media firm must be "hardcore" if they want to stay, reports say.",
Copy after login

需要转义为:

"description": "elon musk says workers at the social media firm must be \"hardcore\" if they want to stay, reports say.",
Copy after login

我不熟悉 golang 的 handlebars,但假设它与常规 handlebars 兼容,您可以注册一个辅助函数来正确转义双引号,以便使用,例如:

"description": "{{{escapequotes .description}}}",
Copy after login

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

Handlebars.registerHelper('escapeQuotes', function (aString) {
    return aString.replace(/"/g, '\\"');
});
Copy after login

您可以在 handlebars 游乐场上尝试一下,网址为 https://www.php.cn/link/fd92a703e837c873aca02bf1edfafcfe一个>

The above is the detailed content of When formatting JSON using JavaScript, I get an error due to the '(double quote) flag in the data. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

PostgreSQL monitoring method under Debian PostgreSQL monitoring method under Debian Apr 02, 2025 am 07:27 AM

This article introduces a variety of methods and tools to monitor PostgreSQL databases under the Debian system, helping you to fully grasp database performance monitoring. 1. Use PostgreSQL to build-in monitoring view PostgreSQL itself provides multiple views for monitoring database activities: pg_stat_activity: displays database activities in real time, including connections, queries, transactions and other information. pg_stat_replication: Monitors replication status, especially suitable for stream replication clusters. pg_stat_database: Provides database statistics, such as database size, transaction commit/rollback times and other key indicators. 2. Use log analysis tool pgBadg

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

How to specify the database associated with the model in Beego ORM? How to specify the database associated with the model in Beego ORM? Apr 02, 2025 pm 03:54 PM

Under the BeegoORM framework, how to specify the database associated with the model? Many Beego projects require multiple databases to be operated simultaneously. When using Beego...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

See all articles