导入数据库失败, Error: Poll error, 导入数据任务(id:346540)异常,错误信息:解析导入文件错误,请检查导入文件内容,仅支持导入json格式数据及excel文件,错误详情如下: JSON decoder out of sync - data changing underfoot?
开通云开发模块
数据库模块添加集合books
导入官方文档案例提供的数据
导入记录报错
第一次导入的时候是直接复制官方文档中的数据,结果直接报错:JSON decoder out of sync - data changing underfoot。
经过文档查阅后修改为下面json代码的格式,就可以成功导入了。
导入JSON格式的要求
- JSON文件必须是 UTF-8 的编码格式,且其内容类似 MongoDB 的导出格式
- JSON 数据不是数组,而是类似 JSON Lines,即各个记录对象之间使用 \n 分隔,而非逗号
- JSON 数据每个键值对的键名首尾不能是 .,例如 “.a”、“abc.”,且不能包含多个连续的 .,例如 “a…b”
- 键名不能重复,且不能有歧义,例如 {“a”: 1, “a”: 2} 或 {“a”: {“b”: 1}, “a.b”: 2}
- 时间格式须为 ISODate 格式,例如 “date”: { “$date” : “2018-08-31T17:30:00.882Z” }
修改格式后重新导入才成功
- 各个记录对象之间使用 \n 分隔,而非逗号
- 去除最外层的[]
{
"_id": "Wzh76lk5_O_dt0vO",
"title": "The Catcher in the Rye",
"author": "J. D. Salinger",
"characters": [
"Holden Caulfield",
"Stradlater",
"Mr. Antolini"
],
"publishInfo": {
"year": 1951,
"country": "United States"
}
}
{
"_id": "Wzia0lk5_O_dt0vR",
"title": "The Lady of the Camellias",
"author": "Alexandre Dumas fils",
"characters": [
"Marguerite Gautier",
"Armand Duval",
"Prudence",
"Count de Varville"
],
"publishInfo": {
"year": 1848,
"country": "France"
}
}
Node.js 把 JSON 数组转换成符合小程序的要求
const fs = require('fs');
// 读取 json 数据
let jsons = fs.readFileSync('./contents.json', 'utf-8');
jsons = JSON.parse(jsons);
// 将 json 数组转换成字符串
let str = '';
for (const item of jsons) {
// 必须使用 \n 换行区别每个记录
str += JSON.stringify(item) + "\n";
}
// 保存到本地
fs.writeFileSync('./test2.json', str);