使用转义的unicode字符解析JSON显示错误



我已经从Instagram下载了JSON数据,我正在NodeJS中解析并存储在MongoDB中。我有一个问题,转义的unicode字符在客户端显示时不显示正确的表情符号。

例如,下面是我正在解析和存储的JSON文件中的一个属性:

"title": "@mujenspirits is in the house!NEW York City u00f0u009fu0097u00bdu00f0u009fu008du008e nImperial Vintner Liquor Store"

上面的例子应该像这样显示:

@mujenspirits在屋里!纽约市🗽🍎Imperial Vintner Liquor Store

但是看起来像这样:

@mujenspirits在屋里!纽约市ðŸ -½ðŸŽImperial Vintner Liquor Store

我发现另一个SO问题,有人有一个类似的问题,他们的解决方案为我在控制台使用一个简单的字符串,但当使用JSON.parse仍然给出相同的不正确的显示。这就是我现在用来解析JSON文件的。

export default function parseJsonFile(filepath: string) {
const value = fs.readFileSync(filepath)
const converted = new Uint8Array(
new Uint8Array(Array.prototype.map.call(value, (c) => c.charCodeAt(0)))
)
return JSON.parse(new TextDecoder().decode(converted))
}

为了后人,我发现了一个额外的SO问题类似于我的。然而,没有解决办法,其中一条评论说:

JSON文件生成错误。字符串将Unicode码点表示为转义码,但将UTF-8数据解码为Latin1

评论者建议将加载的JSON编码为latin1,然后解码为utf8,但这对我也不起作用。

import buffer from 'buffer'
const value = fs.readFileSync(filepath)
const buffered = buffer.transcode(value, 'latin1', 'utf8')
return JSON.parse(buffered.toString())

我对字符编码几乎一无所知,所以在这一点上我是在黑暗中寻找一个解决方案。

一个简单的解决方案是使用uft8包

解码字符串。
npm install utf8

使用现在作为一个例子,看看这个代码使用nodejs和表达:

import express from "express";
import uft8 from "utf8";
const app = express();
app.get("/", (req, res) => {
const text = "u00f0u009fu0097u00bdu00f0u009fu008du008e it is a test";
const textDecode = uft8.decode(text);
console.log(textDecode);
res.send(textDecode);
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log("Server on port 5000");
});

结果是,在localhost:5000中,您将毫无问题地看到表情符号。你可以把这个想法应用到你的项目中,用表情符号来处理json。

下面是客户端的一个例子:

const element= document.getElementById("text")
const txt = "u00f0u009fu0097u00bdu00f0u009fu008du008e it is a test"
const text= utf8.decode(txt)
console.log(text)
element.innerHTML= text
<script src="https://cdnjs.cloudflare.com/ajax/libs/utf8/2.1.1/utf8.min.js" integrity="sha512-PACCEofNpYYWg8lplUjhaMMq06f4g6Hodz0DlADi+WeZljRxYY7NJAn46O5lBZz/rkDWivph/2WEgJQEVWrJ6Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<p id="text"></p>

您可以尝试在解析JSON之前将unicode转义序列转换为字节;也许,utf8.js库可以帮助你。

或者,您发现的解决方案应该工作,但是只有在非系列化JSON(每个unicode转义序列,它将变成一个字符)。因此,您需要遍历对象并将解决方案应用于每个字符串

例如:

function parseJsonFile(filepath) {
const value = fs.readFileSync(filepath);
return decodeUTF8(JSON.parse(value));
}
function decodeUTF8(data) {
if (typeof data === "string") {
const utf8 = new Uint8Array(
Array.prototype.map.call(data, (c) => c.charCodeAt(0))
);
return new TextDecoder("utf-8").decode(utf8);
}
if (Array.isArray(data)) {
return data.map(decodeUTF8);
}
if (typeof data === "object") {
const obj = {};
Object.entries(data).forEach(([key, value]) => {
obj[key] = decodeUTF8(value);
});
return obj;
}
return data;
}

最新更新