Tengo un problema al obtener un archivo .json
en expresar y mostrar en una vista. Amablemente comparte tus ejemplos.Cómo obtener un archivo json en js expresar y mostrar en vista
Respuesta
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');
Este me funcionó. Usando el modulo 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);
}
});
}
Uso:
readJSONFile('../../data.json', function (err, json) {
if(err) { throw err; }
console.log(json);
});
Estoy usando exactamente esto y obteniendo 'if (err) {throw err; } SyntaxError: token inesperado} ' – Piet
hacer algo como esto en su controlador.
Para obtener la JSON contenido de archivo:
ES5 var foo = require('path/to/your/file.json');
ES6 import foo from '/path/to/your/file.json'
;
Para enviar la JSON a la vista:
function getJson(req, res, next){
res.send(foo);
}
Esto debería enviar el JSON contenido a la vista a través de una solicitud.
NOTA
Según 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.
Tenga en cuenta que para los archivos locales, necesita el punto/barra anterior adjunto al requerimiento'./' –
- 1. ¿Cómo obtener JSON de PHP a JS?
- 2. Cómo mostrar un archivo PDF en una vista de Django
- 3. Crear el archivo JSON en línea y obtener la URL
- 4. Vista de lista y adaptadores de lista para mostrar json
- 5. CodeIgniter: ¿Cómo incluyo un archivo .js a la vista?
- 6. Obtener VS JavaScript IntelliSense para js en un archivo diferente
- 7. ¿Cómo puedo obtener la URL del archivo JS en el mismo archivo JS?
- 8. ¿Cómo incluir el archivo js en otro archivo js?
- 9. ¿Cómo debo incluir un archivo js de otro archivo js?
- 10. Obtener y analizar JSON en Actionscript
- 11. Asp.Net script en un archivo js externo
- 12. ¿Cómo usar un archivo .js?
- 13. Cómo usar un archivo JSON en javascript
- 14. Manejo de JSON en plantilla JS/ERB en Rails 3
- 15. ¿Usa etiquetas ASP.Net en un archivo .js?
- 16. ¿Cómo mostrar un archivo jpg en Python?
- 17. Cómo mostrar/ocultar una vista en EmberJS
- 18. jQuery en CodeIgniter, dentro de la vista o en un archivo js externo?
- 19. Herencia de Prototypal en JS y cómo obtener propiedades principales
- 20. ¿Cómo mostrar un mensaje de error JSON?
- 21. Backbone.js - Obtener matriz JSON en la plantilla de vista
- 22. Incluyendo un archivo .js dentro de un archivo .js
- 23. ¿Cómo mostrar varios videos en vista única?
- 24. rieles - cómo hacer que un objeto JSON en una vista
- 25. javascript document.write en un archivo js externo
- 26. En Rails, ¿cómo renderizas JSON usando una vista?
- 27. cómo acceder a js gama definida en otro archivo js
- 28. Archivo JS de referencia en Otro archivo JS e Intellisense
- 29. Cómo agregar jQuery en el archivo JS
- 30. ¿Cómo incluir jquery.js en otro archivo js?
este es el mismo que 'require ('./ config.json')' – Blowsie
esto estaba relacionado con Node.js versiones inferior a V0. 5.x http://stackoverflow.com/questions/7163061/is-there-a-require-for-json-in-node-js – Brankodd
'fs.readFile()' no es lo mismo que 'require()' . Si intenta leer el archivo dos veces con 'fs.readFile()', obtendrá dos punteros diferentes en la memoria. Pero si 'require()' con la misma cadena, señalará el mismo objeto en la memoria, debido al comportamiento de caché de 'required()'. Esto puede conducir a resultados inesperados: cuando la modificación del objeto al que hace referencia el primer puntero cambia inesperadamente el objeto modificado por el segundo puntero. – steampowered