我在獲取.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