简体   繁体   中英

Double quote escaping for valid JSON

I have a string say - this is a "string that needs" escaping" . This string ultimately gets saved in a JSON object so the double quotes must be escaped properly.

I've implemented a utility function to escape it -

export function escapeJsonString(str) {
  // eslint-disable-next-line no-useless-escape
  return str.replace(/"/g, '\"');
}

The output form this is exactly what I need - this is a \"string that needs\" escaping . However, eslint complains that the escape character is useless?

Is there a better way to do this while ensuring I am compliant with ESLint? I'd prefer not to turn off this rule.

Well in this case, you can do this.

'this is a \\"string that needs\\" escaping'

ESLint does not complain about this.

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.

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