简体   繁体   中英

How to convert JSON escaped string into plain HTML-compatible string

I am using an API to compile code, and when there is an error, the response containing the error message uses JSON escape characters, but when outputting it back into the HTML front-end, it just produces garbage characters. How can I either convert the escaped string to a plain text string using Javascript, or output it in HTML correctly?

This is what the string looks like properly outputted (in Powershell):

https://i.imgur.com/tv0BZFl.jpg

This is the escaped string:

\\:\\ In function '\\in...

This is what the string looks like if I directly output it in HTML:

[01m[K:[m[K In function '[01m[Kint main()[m[K': [01m[K:9:1:[m[K [01;31m[Kerror: [m[Kexpected '[01m[K;[m[K' before '[01m[K}[m[K' token } [01;32m[K ^[m[K

Looks like you can use the strip-ansi package. Here's an example using your escaped string:

const stripAnsi = require('strip-ansi');

stripAnsi("\u001b[01m\u001b[K:\u001b[m\u001b[K In function '\u001b[01m\u001b[Kin...")

// result => ": In function 'in..."

If you aren't using node.js, or cannot use that package for whatever reason, this Stack Overflow answer has a regular expression you may be able to use instead.

Just found this tool too:

https://www.npmjs.com/package/ansi-to-html

which converts ANSI to html.

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