简体   繁体   中英

Can't parse JSON file - Unexpected token

I've created json file using Visual studio:

{
  "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

When I try to read package.json, it is read correctly. Does anyone know why I can't read my file?

You have 2 options

add encoding option

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. Otherwise it returns a buffer.

require json

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.

I hope this code help u

$.getJSON("/files/test.json", function(json) {

alert(json['test'])
//if massage show 'object object' then firs purse
//json=JSON.parse(json) //alert(json['test']) });

Solution of the problem is opening file in notepad++ and saving it without BOM. Looks like json created via visual studio adds BOM

It looks like this is not properly formatted JSON. They modifying it like this.

var myObject = {
        'test': 'asd'
    };

and then you parse would be....

 var obj = JSON.parse(myObject);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM