[英]Can't parse JSON file - Unexpected token
I've created json file using Visual studio: 我已经使用Visual Studio创建了json文件:
{
"test": "asd"
}
Using this code to read it: 使用此代码读取它:
var test = fs.readFileSync('./files/test.json')
var obj = JSON.parse(test);
which results in error: Unexpected token in JSON at position 0
导致错误:
Unexpected token in JSON at position 0
When I try to read package.json, it is read correctly. 当我尝试读取package.json时,它被正确读取。 Does anyone know why I can't read my file?
有谁知道为什么我无法读取我的文件?
You have 2 options 您有2个选择
encoding
option encoding
选项 var test = fs.readFileSync('./files/test.json', {encoding: 'utf8'})
var obj = JSON.parse(test);
If the encoding option is specified then this function returns a string.
如果指定了encoding选项,则此函数返回一个字符串。 Otherwise it returns a buffer.
否则,它将返回一个缓冲区。
var obj = require('./files/test.json');
As of node v0.5.x yes you can require your JSON just as you would require a js file.
从节点v0.5.x开始,您可以像需要js文件一样要求JSON。
I hope this code help u 我希望这段代码对您有帮助
$.getJSON("/files/test.json", function(json) {
$ .getJSON(“ / files / test.json”,function(json){
alert(json['test'])
警报(json ['test'])
//if massage show 'object object' then firs purse//如果按摩显示“对象对象”,则触发钱包
//json=JSON.parse(json) //alert(json['test']) });//json=JSON.parse(json)// alert(json ['test'])});
Solution of the problem is opening file in notepad++ and saving it without BOM. 解决该问题的方法是在notepad ++中打开文件并保存而不包含BOM。 Looks like json created via visual studio adds BOM
看起来像通过Visual Studio创建的json添加了BOM
It looks like this is not properly formatted JSON. 看来这是格式不正确的JSON。 They modifying it like this.
他们这样修改它。
var myObject = {
'test': 'asd'
};
and then you parse would be.... 然后您将解析...
var obj = JSON.parse(myObject);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.