typescript引入專案同步json檔案方法總結
思考以下問題
一:用什麼方法在typescript中讀取json檔案
二:路徑設定,相對路徑、絕對路徑怎麼引入,因為路徑不正確肯定會提示找不到模組
三:為什麼
var data = require(‘/sandbox/project/sync/name.json’)
var tmp = JSON.parse(data);
執行時總報Unexpected token o in JSON at position 1
解決思路
一:import方法不好用,node還是用require引入模組吧
二:絕對路徑 require(‘/sandbox/project/sync/name.json’)
相對路徑 require('./name.json')
注意require的路徑格式和import不一樣,試了很長時間
三:被這個問題困擾了很久,在stackoverflow上找到類似問題
The JSON you posted looks fine, however in your code, it is most likely not a JSON string anymore, but already a JavaScript object. This means, no more parsing is necessary.
You can test this yourself, e.g. in Chrome’s console:
new Object().toString()
// “[object Object]”
JSON.parse(new Object())
// Uncaught SyntaxError: Unexpected token o in JSON at position 1
JSON.parse(“[object Object]”)
// Uncaught SyntaxError: Unexpected token o in JSON at position 1
JSON.parse() converts the input into a string. The toString() method of JavaScript objects by default returns [object Object], resulting in the observed behavior.
Try the following instead:
var newData = userData.data.userList;
意思是說,通過require引入的data已經是javascript物件了,你再parse它自然報錯了。
可以這樣證明:
console.log(data);//報同樣的錯誤
var myJson = JSON.stringify(data);
console.log(myJson); //會列印json中的資料