{vardata=p.textcontent;p.textcontent=json.stringify(json.parse(data),null ,2);}); However, when there are double quotes (") in the data"/> {vardata=p.textcontent;p.textcontent=json.stringify(json.parse(data),null ,2);}); However, when there are double quotes (") in the data">
search
HomeBackend DevelopmentGolangWhen formatting JSON using JavaScript, I get an error due to the '(double quote) flag in the data

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

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

问题内容

我使用以下代码片段,在页面上清晰地显示 <pre class="brush:php;toolbar:false"></pre> 标记中的所有 json 字符串,其中 id="jsontext"

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 中有问题的字段是“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
.
.
.

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

这是 <pre class="brush:php;toolbar:false"></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}}}

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

注意: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
}

输出:

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}

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

方法 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.",

需要转义为:

"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 游乐场上尝试一下,网址为 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
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete
Using init for Package Initialization in GoUsing init for Package Initialization in GoApr 24, 2025 pm 06:25 PM

In Go, the init function is used for package initialization. 1) The init function is automatically called when package initialization, and is suitable for initializing global variables, setting connections and loading configuration files. 2) There can be multiple init functions that can be executed in file order. 3) When using it, the execution order, test difficulty and performance impact should be considered. 4) It is recommended to reduce side effects, use dependency injection and delay initialization to optimize the use of init functions.

Go's Select Statement: Multiplexing Concurrent OperationsGo's Select Statement: Multiplexing Concurrent OperationsApr 24, 2025 pm 05:21 PM

Go'sselectstatementstreamlinesconcurrentprogrammingbymultiplexingoperations.1)Itallowswaitingonmultiplechanneloperations,executingthefirstreadyone.2)Thedefaultcasepreventsdeadlocksbyallowingtheprogramtoproceedifnooperationisready.3)Itcanbeusedforsend

Advanced Concurrency Techniques in Go: Context and WaitGroupsAdvanced Concurrency Techniques in Go: Context and WaitGroupsApr 24, 2025 pm 05:09 PM

ContextandWaitGroupsarecrucialinGoformanaginggoroutineseffectively.1)ContextallowssignalingcancellationanddeadlinesacrossAPIboundaries,ensuringgoroutinescanbestoppedgracefully.2)WaitGroupssynchronizegoroutines,ensuringallcompletebeforeproceeding,prev

The Benefits of Using Go for Microservices ArchitectureThe Benefits of Using Go for Microservices ArchitectureApr 24, 2025 pm 04:29 PM

Goisbeneficialformicroservicesduetoitssimplicity,efficiency,androbustconcurrencysupport.1)Go'sdesignemphasizessimplicityandefficiency,idealformicroservices.2)Itsconcurrencymodelusinggoroutinesandchannelsallowseasyhandlingofhighconcurrency.3)Fastcompi

Golang vs. Python: The Pros and ConsGolang vs. Python: The Pros and ConsApr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang and C  : Concurrency vs. Raw SpeedGolang and C : Concurrency vs. Raw SpeedApr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Why Use Golang? Benefits and Advantages ExplainedWhy Use Golang? Benefits and Advantages ExplainedApr 21, 2025 am 12:15 AM

Reasons for choosing Golang include: 1) high concurrency performance, 2) static type system, 3) garbage collection mechanism, 4) rich standard libraries and ecosystems, which make it an ideal choice for developing efficient and reliable software.

Golang vs. C  : Performance and Speed ComparisonGolang vs. C : Performance and Speed ComparisonApr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools