[json] is there a require for json in node.js

I would like to include a couple of JSON files in my JavaScript code that are in the same directory as my JavaScript source file.

If I wanted to include another JavaScript file I could simply use require. Now I'm using readFileSync and __dirname to get the JSON, which I think is an ugly way to do it.

Is there something similar for require that enables me to load a JSON file?

This question is related to json node.js require

The answer is


JSON files don’t require an explicit exports statement. You don't need to export to use it as Javascript files.

So, you can use just require for valid JSON document.

data.json

{
  "name": "Freddie Mercury"
}

main.js

var obj = require('data.json');

console.log(obj.name); 
//Freddie Mercury

A nifty non-caching async one liner for node 15 modules:

import { readFile } from 'fs/promises';

const data = await readFile('{{ path }}').then(json => JSON.parse(json)).catch(() => null);

You even can use require of your JSON without specifying the extension .json. It will let you change the file extension to .js without any changes in your imports.

assuming we have ./myJsonFile.json in the same directory.

const data = require('./myJsonFile')

If in the future you'll change ./myJsonFile.json to ./myJsonFile.js nothing should be changed in the import.


No. Either use readFile or readFileSync (The latter only at startup time).

Or use an existing library like

Alternatively write your config in a js file rather then a json file like

module.exports = {
  // json
}

Two of the most common

First way :

let jsonData = require('./JsonFile.json')

let jsonData = require('./JsonFile') // if we omitting .json also works

OR

import jsonData from ('./JsonFile.json')

Second way :

1) synchronously

const fs = require('fs')
let jsonData = JSON.parse(fs.readFileSync('JsonFile.json', 'utf-8'))

2) asynchronously

const fs = require('fs')
let jsonData = {}
fs.readFile('JsonFile.json', 'utf-8', (err, data) => {
  if (err) throw err

  jsonData = JSON.parse(data)
})

Note: 1) if we JsonFile.json is changed, we not get the new data, even if we re run require('./JsonFile.json')

2) The fs.readFile or fs.readFileSync will always re read the file, and get changes


You can import json files by using the node.js v14 experimental json modules flag. More details here

file.js

import data from './folder/file.json'

export default {
  foo () {
    console.log(data)
  }
}

And you call it with node --experimental-json-modules file.js


Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to require

The difference between "require(x)" and "import x" PHP - Failed to open stream : No such file or directory cannot redeclare block scoped variable (typescript) NodeJs : TypeError: require(...) is not a function Include PHP file into HTML file How to make node.js require absolute? (instead of relative) Ruby 'require' error: cannot load such file Nodejs cannot find installed module on Windows is there a require for json in node.js node.js require all files in a folder?