小程序云开发的开通及json数据导入并解决导入数据库失败JSON decoder out of sync - data changing underfoot

导入数据库失败, Error: Poll error, 导入数据任务(id:346540)异常,错误信息:解析导入文件错误,请检查导入文件内容,仅支持导入json格式数据及excel文件,错误详情如下: JSON decoder out of sync - data changing underfoot?

开通云开发模块

开通云开发功能

数据库模块添加集合books

数据库模块 添加集合名称books

导入官方文档案例提供的数据

官方案例的数据
官方文档-示例的集合数据

导入记录报错

第一次导入的时候是直接复制官方文档中的数据,结果直接报错:JSON decoder out of sync - data changing underfoot。
经过文档查阅后修改为下面json代码的格式,就可以成功导入了。

小程序JSON decoder out of sync - data changing underfoot

导入JSON格式的要求

  1. JSON文件必须是 UTF-8 的编码格式,且其内容类似 MongoDB 的导出格式
  2. JSON 数据不是数组,而是类似 JSON Lines,即各个记录对象之间使用 \n 分隔,而非逗号
  3. JSON 数据每个键值对的键名首尾不能是 .,例如 “.a”、“abc.”,且不能包含多个连续的 .,例如 “a…b”
  4. 键名不能重复,且不能有歧义,例如 {“a”: 1, “a”: 2} 或 {“a”: {“b”: 1}, “a.b”: 2}
  5. 时间格式须为 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"
	}
}

小程序重新导入json

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);

相关链接

云开发-官方文档
数据库导入格式要求-官方文档

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章