小程序雲開發的開通及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);

相關鏈接

雲開發-官方文檔
數據庫導入格式要求-官方文檔

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