{vardata=p.textcontent;p.textcontent=json.stringify(json.parse(data),null,2);});但是,当数据中存在双引号(")"/> {vardata=p.textcontent;p.textcontent=json.stringify(json.parse(data),null,2);});但是,当数据中存在双引号(")">
搜索
首页后端开发Golang使用 JavaScript 格式化 JSON 时,由于数据中的'(双引号)标志,我收到错误

使用 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一个>

以上是使用 JavaScript 格式化 JSON 时,由于数据中的'(双引号)标志,我收到错误的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:stackoverflow。如有侵权,请联系admin@php.cn删除
在Golang和Python之间进行选择:适合您的项目在Golang和Python之间进行选择:适合您的项目Apr 19, 2025 am 12:21 AM

golangisidealforperformance-Critical-clitageAppations and ConcurrentPrompromming,而毛皮刺激性,快速播种和可及性。1)forhigh-porformanceneeds,pelectgolangduetoitsefefsefefseffifeficefsefeflicefsiveficefsiveandconcurrencyfeatures.2)fordataa-fordataa-fordata-fordata-driventriventriventriventriventrivendissp pynonnononesp

Golang:并发和行动绩效Golang:并发和行动绩效Apr 19, 2025 am 12:20 AM

Golang通过goroutine和channel实现高效并发:1.goroutine是轻量级线程,使用go关键字启动;2.channel用于goroutine间安全通信,避免竞态条件;3.使用示例展示了基本和高级用法;4.常见错误包括死锁和数据竞争,可用gorun-race检测;5.性能优化建议减少channel使用,合理设置goroutine数量,使用sync.Pool管理内存。

Golang vs. Python:您应该学到哪种语言?Golang vs. Python:您应该学到哪种语言?Apr 19, 2025 am 12:20 AM

Golang更适合系统编程和高并发应用,Python更适合数据科学和快速开发。1)Golang由Google开发,静态类型,强调简洁性和高效性,适合高并发场景。2)Python由GuidovanRossum创造,动态类型,语法简洁,应用广泛,适合初学者和数据处理。

Golang vs. Python:性能和可伸缩性Golang vs. Python:性能和可伸缩性Apr 19, 2025 am 12:18 AM

Golang在性能和可扩展性方面优于Python。1)Golang的编译型特性和高效并发模型使其在高并发场景下表现出色。2)Python作为解释型语言,执行速度较慢,但通过工具如Cython可优化性能。

Golang vs.其他语言:比较Golang vs.其他语言:比较Apr 19, 2025 am 12:11 AM

Go语言在并发编程、性能、学习曲线等方面有独特优势:1.并发编程通过goroutine和channel实现,轻量高效。2.编译速度快,运行性能接近C语言。3.语法简洁,学习曲线平缓,生态系统丰富。

Golang和Python:了解差异Golang和Python:了解差异Apr 18, 2025 am 12:21 AM

Golang和Python的主要区别在于并发模型、类型系统、性能和执行速度。1.Golang使用CSP模型,适用于高并发任务;Python依赖多线程和GIL,适合I/O密集型任务。2.Golang是静态类型,Python是动态类型。3.Golang编译型语言执行速度快,Python解释型语言开发速度快。

Golang vs.C:评估速度差Golang vs.C:评估速度差Apr 18, 2025 am 12:20 AM

Golang通常比C 慢,但Golang在并发编程和开发效率上更具优势:1)Golang的垃圾回收和并发模型使其在高并发场景下表现出色;2)C 通过手动内存管理和硬件优化获得更高性能,但开发复杂度较高。

Golang:云计算和DevOps的关键语言Golang:云计算和DevOps的关键语言Apr 18, 2025 am 12:18 AM

Golang在云计算和DevOps中的应用广泛,其优势在于简单性、高效性和并发编程能力。1)在云计算中,Golang通过goroutine和channel机制高效处理并发请求。2)在DevOps中,Golang的快速编译和跨平台特性使其成为自动化工具的首选。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热工具

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用