An administrator has directly filled content into the database and formatted it as json string. However, when retrieving it from the database and parse it into json, it failed. Because when filling data directly, instead of content need to write this ( \\"
), they just write ( "
) the json string shield is faulty and cannot parse. 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"'
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).
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
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"
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.