如何将从文件读取的JSON数据转换为JSON对象

时间:2017-03-30 06:57:41

标签: javascript json

我想将一个从文件读取的JSON对象传递给POST api。但是,我看到当从文件中读取它然后它无法正常工作。但是,当硬编码的JSON数据通过时,它正在工作。为了让您更好地理解,我给出了以下代码示例:

var json_content = {};
fs.readfile(file, function(err, data) {
        json_content = data;
        console.log("typeof json_variable  = "+ typeof json_content + "| json_content ="+json_content);
        if(err) {
            console.log("file reading error is = "+err);
            return;
        }
}

上面的console.log语句的输出如下:

typeof json_variable = object | json_content = {'title':'adventure','name':'Homes'}

当我使用superagent将这个json_content发送到我作为一个身体的帖子调用时,它无效。实际上在服务器中,如果我执行req.body.title

,它将被接收为undefined

然而,不是上面的机制,我从文件中读取它并发送,如果我将json_content变量设置为硬编码值,那么它工作正常。下面是代码和输出:

json_content = {'title' : 'adventure', 'name': 'Homes'};
console.log("typeof json_variable  = "+ typeof json_content + "| json_content ="+json_content);

此次输出不同,如下所示:

typeof json_variable = object | json_content = [object Object]

请注意输出的差异,因为json_content现在打印为[object Object],而不像以前打印整个JSON的情况。

请您建议,当我从文件中读取文件并将其发送到帖子以获得类似的效果时,我需要更改第一种方法,以便在编写json时获得类似的效果?

1 个答案:

答案 0 :(得分:1)

它们之间的唯一区别是一个是对象的字符串表示,而第二个是javascript对象。



var json_content = '[{"key":"value"}]';
console.log("json_content"+json_content);

var json_content = [{"key":"value"}];
console.log("json_content"+json_content);




您的代码中还发生了另一件事:您在+语句中使用了连接console.log()
对我来说,你应该避免使用这种方式,而是尝试使用,



var json_content = '[{"key":"value"}]';
console.log("json_content", json_content);

var json_content = [{"key":"value"}];
console.log("json_content", json_content);




您的最后评论:



var json_content = '[{"key":"value"}]';
json_content = JSON.parse('[{"key":"value"}]');
console.log("json_content"+json_content);




相关问题