解析Protobuf文件并转为JSON格式
我们知道 Protobuf 文件可以减少体积,方便存储和传输,但在获取文件后,我们还需要将其转换为 JSON 格式,以适配应用进行处理数据。 下面的代码是在微信小程序中使用,将 pb 文件转换为 JSON,然后再使用。 // 小程序根目录执行安装(需开启 npm 支持) // npm install protobufjs // 创建 proto 文件 /proto/item.proto /* syntax = "proto3"; message DataItem { string id = 1; string name = 2; string kw = 3; bool lock = 4; string category = 5; string label = 6; int32 grade = 7; } message DataArray { repeated DataItem items = 1; } */ // 在 app.js 中引入 const protobuf = require('protobufjs'); // 页面 JS 文件 Page({ data: { items: [] }, onLoad() { this.loadProtoData(); }, async loadProtoData() { try { // 1. 下载二进制文件 const { tempFilePath } = await this.downloadFile(); // 2. 读取文件内容 const arrayBuffer = await this.readFile(tempFilePath); // 3. 加载 Proto 定义 const root = await protobuf.load('/proto/item.proto'); const DataArray = root.lookupType('DataArray'); // 4. 解析数据 const decoded = DataArray.decode(new Uint8Array(arrayBuffer)); // 5. 转换格式 const result = decoded.items.map(item => ({ id: item.id || '', name: item.name || '', kw: item.kw || '', lock: typeof item.lock === 'boolean' ? item.lock : false, category: item.category || '', label: item.label || '', grade: item.grade || 1 })); this.setData({ items: result }); } catch (err) { console.error('解析失败:', err); } }, downloadFile() { return new Promise((resolve, reject) => { wx.downloadFile({ url: 'https://your-domain.com/data.bin', success: resolve, fail: reject }); }); }, readFile(tempFilePath) { return new Promise((resolve, reject) => { wx.getFileSystemManager().readFile({ filePath: tempFilePath, encoding: 'binary', success: res => resolve(res.data), fail: reject }); }); } }); 当文件非常大时,解析速度会有点慢啊,为了更进一步的提高速度,我们可以使用 WebAssembly,这里是一个 Wasm 示例: ...