node.js 读取文件后解析json为什么总是报错?


文件data.txt的内容

{"title":"Hello","content":"nihao","id":1439883748614}
{"title":"Hello","content":"nihao","id":1439883789405}
{"title":"Hello","content":"nihao","id":1439883893949}
{"title":"Hello","content":"nihao","id":1439883895058}
{"title":"Hello","content":"nihao","id":1439883896144}

js代码:


 var fs=require('fs');
    fs.readFile('./data/data.txt','utf-8',function(err,data){  
        if(err){
            console.log("error");  
        }else{
            var array=data.split('\n');
            for (var i = 0; i < array.length; i++) {
                var str=array[i];
                console.log(str);
                var b=JSON.parse(str);
            }
        }  
    });

明明是标准的json,为什么老是报错?错误:

SyntaxError: Unexpected end of input


 at Object.parse (native)
at C:\Users\***\Documents\GitHub\Eyas\control\handle.js:44:19
at fs.js:334:14
at FSReqWrap.oncomplete (fs.js:95:15)

node.js node

工程塑料113 9 years, 8 months ago

自己回答:找到原因了,写文件的时候最后多生成了一个空行,晕死。。。。

莉莉丝七重奏 answered 9 years, 8 months ago

Your Answer