我在获取.json
文件时出现问题并在视图中显示。请分享你的例子。如何获取JSON文件并显示在视图中
回答
var fs = require("fs"),
json;
function readJsonFileSync(filepath, encoding){
if (typeof (encoding) == 'undefined'){
encoding = 'utf8';
}
var file = fs.readFileSync(filepath, encoding);
return JSON.parse(file);
}
function getConfig(file){
var filepath = __dirname + '/' + file;
return readJsonFileSync(filepath);
}
//assume that config.json is in application root
json = getConfig('config.json');
这一个为我工作。使用FS模块:
var fs = require('fs');
function readJSONFile(filename, callback) {
fs.readFile(filename, function (err, data) {
if(err) {
callback(err);
return;
}
try {
callback(null, JSON.parse(data));
} catch(exception) {
callback(exception);
}
});
}
用法:
readJSONFile('../../data.json', function (err, json) {
if(err) { throw err; }
console.log(json);
});
我正在使用这一点,并得到'if(err){throw err; } SyntaxError:Unexpected token}' – Piet
做这样的事情在你的控制器。
要获得的JSON文件的内容:
ES5 var foo = require('path/to/your/file.json');
ES6 import foo from '/path/to/your/file.json'
;
要发送的JSON到您的视图:
function getJson(req, res, next){
res.send(foo);
}
这应该通过请求JSON内容发送到您的视图。
注意
根据BTMPL
While this will work, do take note that require calls are cached and will return the same object on each subsequent call. Any change you make to the .json file when the server is running will not be reflected in subsequent responses from the server.
请注意,对于本地文件,需要将前面的点/斜线附加到require。。/' –
- 1. 使用json获取图像并在列表视图中显示
- 2. 从URL获取JSON文件并显示
- 3. BackboneJS - 如何获取外部RSS源并在视图中显示
- 4. 我如何获取并显示joomla2.5中的视图文件中的值
- 5. MVC如何调用jQuery获取并获取视图来显示
- 6. 从MYSQL获取数据并显示在JSON文件中
- 7. 如何在web2py视图中获取json
- 8. 如何从.txt文件中读取,并显示在文本视图
- 9. 在视图中显示Json
- 10. 如何获取控制台日志并在文本视图中显示[Swift]
- 11. 如何获取文件名并在列表中显示
- 12. 如何从TextBox中获取输入并在MVC中显示在视图中
- 13. 如何从摄像机显示捕获图像并从文件路径显示在图像视图中?
- 14. 我如何获取json值并在html中显示
- 15. 如何从excel文件读取数据并在我的视图中显示?
- 16. 获取JSON数据并显示在DIV
- 17. 在列表视图中显示视频从Json文件
- 18. 获取视图以显示在LinearLayout中
- 19. Laravel从关系中获取数据并在视图中显示
- 20. 如何从控制器获取JSON在ASP.net MVC 2视图中显示
- 21. 如何获取所选文件的缩略图并在PictureBox中显示?
- 22. 如何从数据库中获取数据并在视图中显示
- 23. rxJava如何从sqlite中获取数据并显示在回收站视图中
- 24. 如何在文本视图中显示“\”
- 25. 获取所有联系人并在列表视图中显示
- 26. 获取最后插入的id codeigniter并在视图中显示
- 27. 从SQLite获取信息并在列表视图中显示
- 28. 从Facebook获取名称并在列表视图中显示
- 29. 如何从SD卡中获取图片并在gridView中显示
- 30. 如何在列表视图中获取SD卡歌曲并在android中显示在列表视图中?
这是一样的'要求( './ config.json')' – Blowsie
这是Node.js的版本比V0低有关。 5.x http://stackoverflow.com/questions/7163061/is-there-a-require-for-json-in-node-js – Brankodd
'fs.readFile()'不同于'require()' 。如果你尝试用'fs.readFile()'读两次文件,你会在内存中得到两个不同的指针。但是如果你用相同的字符串require()',由于require()'的缓存行为,你将指向内存中的同一个对象。这可能会导致意想不到的结果:修改第一个指针引用的对象意外更改第二个指针修改的对象。 – steampowered