![](/img/trans.png)
[英]How to read the data from json file and return as string or object in angularJS?
[英]How to convert a JSON data read from a file as JSON object
我想将一个从文件读取的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,它将作为未定义接收
但是,不是上面的机制(我从文件中读取它并发送),如果我将json_content变量设置为硬编码值,则它可以正常工作。 下面是代码和输出:
json_content = {'title' : 'adventure', 'name': 'Homes'};
console.log("typeof json_variable = "+ typeof json_content + "| json_content ="+json_content);
这次的输出不同,如下所示:
typeof json_variable =对象| json_content = [对象对象]
请注意输出的差异,因为json_content现在被打印为[object Object],这与之前打印整个JSON的情况不同。
您能否提出建议,当我从文件中读取并将其发送到后期以得到与硬编码json时类似的效果时,我该如何更改第一种方法?
它们之间的唯一区别是,一个是对象的字符串表示形式,第二个是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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.