使用 linux 工具将 \u003c 转换为 < 字符

Converting \u003c to < character with linux tools

从一个 ajax 电话中,我得到了这样的回复:

{"d":"\u003cdiv class=\"popup_title\"\u003eBENTELER Autótechnika Kft.\u003c/div\u003e\u003cdiv style=\"font-size:10pt;font-weight:bold;\"\u003e8060 Mór, Akai út 5.

我想将其转换为 "usable" 格式,因此 \u0003c 将只是一个 < 字符。

ajax 调用的 header 表示这是一个 iso-8859-2 编码 (content-type: text/plain; charset=iso-8859-2 ), 但我不确定。

我尝试使用 iconv 有很多选项,但没有成功。

有趣的是,例如这个网站:

https://www.online-toolz.com/tools/text-unicode-entities-convertor.php

不用任何东西就可以解决问题,我就是找不到 "from encoding" 应该是什么。

我很乐意使用 iconv

最简单的方法是使用适合您选择的语言的 JSON 解析器,它将其转换为适当的数据结构并取消转义。您看到的是代表 U+003C 的 Unicode 转义字符,即 < 字符。 JSON 解析器经常转义尖括号,因为它们在 HTML 和 XML 中具有特殊含义,转义它们意味着 JSON 可以按字面意思插入到这些类型的文档中。

或者,如果您想在不处理它们的情况下从命令行转义它们,您可以将其通过管道传递给 Perl 或 Ruby 来执行此操作,如下所示:

perl -pe 's/\u([0-9a-f]+)/"\u{}"/ge;'

ruby -pe '$_.gsub!(/\u([0-9a-f]+)/) { |m| m.to_i(16).chr }'

请注意,您从服务器获得的编码可能是转移注意力的。 JSON 需要使用 Unicode,很可能是服务器配置错误。如果您确定数据实际上在 ISO-8859-2 中,违反了规范,您可以通过将以下命令的输出传送到 perlruby 命令之一来修复它以上:

iconv -f ISO-8859-2 -t UTF-8

字符集就是简单的ASCII。这些是使用的转义码,例如通过 JavaScript(和 Python)。

如果您从 AJAX 调用中获得的值是有效的 JSON(大概是这样),请使用 JSON 工具提取它。

bash$ jq -r .d <<\:
{"d":"\u003cdiv class=\"popup_title\"\u003eBENTELER Autótechnika Kft.\u003c/div\u003e\u003cdiv style=\"font-size:10pt;font-weight:bold;\"\u003e8060 Mór, Akai út 5."}
:
<div class="popup_title">BENTELER Autótechnika Kft.</div><div style="font-size:10pt;font-weight:bold;">8060 Mór, Akai út 5.

您可以使用 Bash 的 printf:

%b 格式化指令
$ encoded='{"d":"\u003cdiv class=\"popup_title\"\u003eBENTELER Autótechnika Kft.\u003c/div\u003e\u003cdiv style=\"font-size:10pt;font-weight:bold;\"\u003e8060 Mór, Akai út 5.'
$ printf -v decoded '%b\n' "$encoded"
$ printf '%s\n' "$decoded"
{"d":"<div class=\"popup_title\">BENTELER Autótechnika Kft.</div><div style=\"font-size:10pt;font-weight:bold;\">8060 Mór, Akai út 5.

来自手册:

%b
Causes printf to expand backslash escape sequences in the corresponding argument in the same way as echo -e (see Bash Builtins).


正如 Charles 在他的评论中指出的那样,%b 并不局限于 Bash 的 printf,而是 required by POSIX; interpretation of \u<i>HHHH</i> escapes, on the other hand, only happens in Bash, as described in the escape sequences for echo.