简体   繁体   English

如何在JavaScript中处理JSON字符串错误(错误字符“”)

[英]How to handle JSON string errors (error character ") in javascript

An administrator has directly filled content into the database and formatted it as json string. 管理员已将内容直接填充到数据库中,并将其格式化为json字符串。 However, when retrieving it from the database and parse it into json, it failed. 但是,当从数据库中检索它并将其解析为json时,它失败了。 Because when filling data directly, instead of content need to write this ( \\" ), they just write ( " ) the json string shield is faulty and cannot parse. 因为当直接填充数据时,而不是内容需要写这个( \\" ),所以他们只是写( " )json字符串屏蔽出现了故障,无法解析。 How to solve this problem. 如何解决这个问题呢。 Ex: 例如:

"aaaa"dddd"aaaa" => "aaaa\"dddd\"aaaa"

I assume that when you retrieve the string from the database, you are getting something like: '"aaaa"dddd"aaaa"' 我假设当您从数据库中检索字符串时,会得到类似'"aaaa"dddd"aaaa"'

If so, then you can convert that to a valid JSON string by removing the first and last double quotes and using JSON.stringify to convert the string to a valid JSON string (including escaping the inner double quotes). 如果是这样,那么您可以通过删除第一个和最后一个双引号,然后使用JSON.stringify将字符串转换为有效的JSON字符串(包括转义内部的双引号),将其转换为有效的JSON字符串。

For example: 例如:

 const s = '"aaaa"dddd"aaaa"'; let escaped = JSON.stringify(s.slice(1, -1)); console.log(escaped); // "aaaa\\"dddd\\"aaaa" let parsed = JSON.parse(escaped); console.log(parsed); // aaaa"dddd"aaaa 

You might use replace with RegExp and g flag 您可以使用带有RegExpg标志的replace

 let str = `"aaaa"dddd"aaaa"`; let result = str.replace(/"/g,`\\\\"`).slice(1,-2) + '"'; console.log(result) 

OP asked My database return result string "aaaa"dddd"aaaa" , How to assign such "aaaa"dddd"aaaa" OP询问我的数据库返回结果字符串"aaaa"dddd"aaaa" ,如何分配此类"aaaa"dddd"aaaa"
You can interpolate that return from database into Template Strings 您可以将从数据库返回的值插入到模板字符串中

let str = `${database.value}`;

Not sure what database or what language is on server side, however, rather that trying to escape the inner quotes. 但是,不确定服务器端使用什么数据库或哪种语言,而是尝试转义内部引号。 Trying just replacing the first and last double quote with with a single quote. 尝试仅用单引号替换第一个和最后一个双引号。 Not sure of the full context here to know whether this is the issue. 不确定此处是否提供完整的上下文以了解这是否是问题所在。 Anyway, something to consider 无论如何,要考虑的事情

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM