20

I have a problem in getting a .json file in express and displaying in a view. Kindly share your examples.

jofftiquez
  • 7,548
  • 10
  • 67
  • 121
PCA
  • 1,677
  • 6
  • 28
  • 45

5 Answers5

34
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');
auroranil
  • 2,621
  • 6
  • 24
  • 34
Brankodd
  • 831
  • 9
  • 21
  • 13
    this is the same as `require('./config.json')` – Blowsie Nov 04 '14 at 09:21
  • this was related to node.js versions lower than v0.5.x http://stackoverflow.com/questions/7163061/is-there-a-require-for-json-in-node-js – Brankodd Mar 16 '16 at 18:29
  • 5
    `fs.readFile()` is not the same as `require()`. If you try to read the file twice with `fs.readFile()`, you will get two different pointers in memory. But if you `require()` with the same string, you will be pointing to the same object in memory, due to caching behavior of `required()`. This can lead to unexpected results: when modifying the object referenced by the first pointer unexpectedly changes the object modified by the second pointer. – steampowered Apr 20 '16 at 03:38
  • @Blowsie this isn't same as `require`. require will throw error on dynamically generated file – master_dodo Aug 11 '17 at 14:09
  • `require` will load all huge files in memory when app starts, even if they are never called or needed for a time period. – Priya Ranjan Singh Aug 09 '21 at 09:46
30

Do something like this in your controller.

To get the json file's content :

ES5 var foo = require('./path/to/your/file.json');

ES6 import foo from './path/to/your/file.json';

To send the json to your view:

function getJson(req, res, next){
    res.send(foo);
}

This should send the json content to your view via a request.

NOTE

According to 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.

jofftiquez
  • 7,548
  • 10
  • 67
  • 121
15

This one worked for me. Using fs module:

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);
    }
  });
}

Usage:

readJSONFile('../../data.json', function (err, json) {
  if(err) { throw err; }
  console.log(json);
});

Source

Jordi Vicens
  • 696
  • 7
  • 17
Arbie Samong
  • 1,195
  • 1
  • 15
  • 17
  • I am using exactly this and getting `if(err) { throw err; } SyntaxError: Unexpected token }` – Piet Jul 27 '15 at 19:39
0

Using import, resolve, toString():

import fs from "fs";
import path from "path";

const boxes_path = path.resolve(__dirname, "boxes.json");
const rawdata = fs.readFileSync(boxes_path);
let data = JSON.parse(rawdata.toString());
rofrol
  • 14,438
  • 7
  • 79
  • 77
0

comparison of sync vs async :

Sync :
Output : file1 -> file2 -> file3
In this file1 is read then it goes to next file does not matter if the file2 size is less than file1. Given file is read in given order.

Aysnc :
file3 is smaller than file1 and file1 is smaller than file2
Output : file3 -> file1 -> file2
In this according to execution time the file is read. For example If the file3 is of less size then file3 will be executed quickly so, its data is available first and likewise the execution will continue.

asynchronous way to read json file :

import fs from "fs";
import path from "path";

//async way to read json file
fs.readFile('demo.json', function(err, data){
    if(err)throw err;
    // Display the file data
    console.log(JSON.parse(data));
});

synchronous way to read :

let jsonObjData;

try {
  const jsonStringData = fs.readFileSync("./demo.json");
  //convert json string data to json object data
  jsonObjData = JSON.parse(jsonStringData);
} catch (err) {
  console.log(err);
}

//Display json data
console.log(jsonObjData);
Jerry
  • 1,005
  • 2
  • 13