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中的数据

你可能感兴趣的:(json解析)