JSON在位置0处的意外令牌u-将JSON字符串数据从文件解析到Web服务器时 [英] Unexpected token u in JSON at position 0 - while parsing JSON string data from file into the web server

查看:187
本文介绍了JSON在位置0处的意外令牌u-将JSON字符串数据从文件解析到Web服务器时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已使用JSON.stringify(data)将Json数据写入文件. 但是,当我使用JSON.parse(data)从文件中读取时,在JSON at position 0中收到错误Unexpected token u.当我打印data

I have written Json data into the file using JSON.stringify(data). but, when I read from the file using JSON.parse(data), I get an error Unexpected token u in JSON at position 0 . It prints Undefined when I print data

function read(req, res) {

    reader.on('data', function (chunk) {
        response += chunk;
    });
    reader.on('end', function () {
        console.log(response);
    })
    reader.on('error', function (err) {
        console.log(err.stack);
    });

}

app.get('/index.html', function (req, res) {
    res.sendFile(__dirname + "/" + "index.html");
})


app.get('/process_get', function (req, res) {
    read(req, res);
    console.log(response);
    res.end(JSON.parse(response)); // Here is the error - reading from file
})


文件中的内容-outputs.txt

从网络路由到文件的代码-

Code to route from web to file -

function write(req, res) {
    response = {
        first_name: req.body.first_name,
        last_name: req.body.last_name

    };
    writer.write(JSON.stringify(response));
}
app.post('/process_post', urlencodedParser, function (req, res) {
    write(req, res);
    console.log(response);
    res.end('Successfully written to file');
})

推荐答案

您正在尝试在读取文件之前解析文件.由于读取内容是异步发生的,因此执行将继续.这意味着response在您调用JSON.parse时是undefined,它需要一个字符串,因此由于没有得到一个而将引发异常.

You're trying to parse the file before you've finished reading it. Since reading the contents happens asynchronously, execution continues. This means response is undefined at the time you call JSON.parse, which requires a string and therefore throws an exception since it's not getting one.

您的read函数需要在读完时发出信号,方法是调用回调(使签名为read(req, res, callback))或返回一个Promise.然后,您的路由应该对回调或Promise的.then()中的文件内容进行任何处理.

Your read function needs to signal when it has finished reading, either by invoking a callback (making the signature read(req, res, callback)) or returning a promise. Then your route should do any processing of the file contents in the callback or the promise's .then().

这篇关于JSON在位置0处的意外令牌u-将JSON字符串数据从文件解析到Web服务器时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆