[英]Keeping escaped unicode characters with JSON.stringify of JSON.parse
I have an input JSON like this (which really contains the literal values " –
" (the encoded form of a unicode character)):我有一个像这样的输入 JSON(它实际上包含文字值“
–
”(unicode 字符的编码形式)):
{"source":"Subject: NEED: 11/5 BNA-MSL \u2013 1200L Departure - 1 Pax"}
I read it with JSON.parse
and it reads the –
as –
, which is fine for display in my app.我用
JSON.parse
读取它,它读取–
as –
,这很适合在我的应用程序中显示。
However, I need to export again the same JSON, to send it down to some other app.但是,我需要再次导出相同的 JSON,以将其发送到其他应用程序。 I want to keep the same format and have back the
–
into the JSON. I am doing JSON.stringify
, but it keeps the –
in the output.我想保持相同的格式并将
–
返回到 JSON。我正在做JSON.stringify
,但它将–
保留在 output 中。
Any idea what I could do to keep the \u
syntax?知道我可以做些什么来保留
\u
语法吗?
Using a replacer function in a JSON.stringify call didn't work - strings returned from the replacer with an escaped backslash produce a double backslash in output, and a single backslashed character is unescaped in output if possible.在JSON.stringify调用中使用替换器 function 无效 - 从替换器返回的带有转义反斜杠的字符串在 output 中产生双反斜杠,如果可能,在 output 中未转义单个反斜杠字符。
Simply re-escaping the stringify
result has potential:简单地重新转义
stringify
结果有可能:
const obj = {"source":"Subject: NEED: 11/5 BNA-MSL – 1200L Departure - 1 Pax"} console.log(" stringify: ", JSON.stringify( obj)); console.log("& replaceAll: ", JSON.stringify(obj).replaceAll('–', '\–'));
using more complex string modifications as necessary.根据需要使用更复杂的字符串修改。
However this looks very like an X solution to an XY problem.然而,这看起来非常像 XY 问题的 X 解决方案。 Better might be to fix the downstream parsing to handle JSON text as JSON text and not try to use it in raw form - particularly given that JSON text in encoded in utf-8 and can handle non-ASCII characters without special treatment.
更好的方法可能是修复下游解析,将 JSON 文本作为 JSON 文本处理,而不是尝试以原始形式使用它——特别是考虑到 JSON 文本以 utf-8 编码并且可以处理非 ASCII 字符而无需特殊处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.