2

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"
1
  • My database return result string "aaaa"dddd"aaaa", How to assign such `"aaaa"dddd"aaaa"`? Commented Mar 12, 2019 at 7:02

3 Answers 3

2

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"';
const escaped = JSON.stringify(s.slice(1, -1));
console.log(escaped);
// "aaaa\"dddd\"aaaa"

const parsed = JSON.parse(escaped);
console.log(parsed);
// aaaa"dddd"aaaa

Sign up to request clarification or add additional context in comments.

Comments

1

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}`;

4 Comments

@gkelly I may have misunderstood. Can you explain what is question?
no dis-respect intended. I answered below. However, I may have mis-understood as well.
@shash678 Now see it I have fixed that
My database return result string "aaaa"dddd"aaaa", How to assign such `"aaaa"dddd"aaaa"`?
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.