微信小程序云开发导入 json 数据错误解决方法
问题重现
使用微信云开发控制台导入 json 数据时,出现错误:
导入数据库失败, Error: Poll error, 导入数据任务(id:269599)异常,错误信息:解析导入文件错误,请检查导入文件内容,仅支持导入json格式数据及excel文件,错误详情如下: JSON decoder out of sync - data changing underfoot?
解决方法:
错误原因是云开发导入的 json 格式不是标准的 json 格式(数组元素使用 , 分隔),而是类 MongoDB 格式,数组每一项使用换行 n 分隔。具体参考 https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/database/import.html
Node.js 把 JSON 数组转换成云开发数据库支持导入格式代码。
const fs = require('fs');
// 读取 json 数据
let jsons = fs.readFileSync('./word.json', 'utf-8');
jsons = JSON.parse(jsons);
// 将 json 数组转换成字符串
let str = '';
for (const item of jsons) {
// 必须使用 \n 换行区别每个记录
str += JSON.stringify(item) + "\n";
}
// 保存到本地
fs.writeFileSync('./words.json', str);