Corno
Corno

Reputation: 5396

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?

Upvotes: 369

Views: 437908

Answers (10)

dreamLo
dreamLo

Reputation: 1880

With node v23 you can import json files by using this:

import data from './folder/file.json' with { type: 'json' }

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

You no longer need the experimental flag and the functionality is now Stable

Upvotes: 18

Igor Litvinovich
Igor Litvinovich

Reputation: 2502

You can even require your JSON file without specifying the extension .json. It will let you change the file extension to .js without changing your import.

Assuming we have myJsonFile.json in the same directory.

const data = require('./myJsonFile')

If, in the future, you change myJsonFile.json to myJsonFile.js, you won't need to change the import.

Upvotes: 7

Raynos
Raynos

Reputation: 169511

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
}

Upvotes: 26

goatslacker
goatslacker

Reputation: 10190

As of Node v0.5.x, yes.

You can require your JSON just as you would require a JS file.

const someObject = require('./somefile.json')

In ES6:

import someObject from './somefile.json'

Upvotes: 618

Rajkumar
Rajkumar

Reputation: 1077

Two of the most common way to import

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 JsonFile.json is changed, we do 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

Upvotes: 55

Chukwunazaekpere
Chukwunazaekpere

Reputation: 1012

Simply use the JSON object from Node; you don't need import it. See usage below:

const jsonifiedObject = JSON.parse(an_array or a_object)
or
JSON.stringify(object)

Hope that helps..

Upvotes: -2

Thnawat Gulati
Thnawat Gulati

Reputation: 101

You can use a module to create a require.

import { createRequire } from 'module'
const require = createRequire(import.meta.url)
const foo = require('./foo.json')

Upvotes: 3

Thiago Dantas
Thiago Dantas

Reputation: 73

if you are using typescript, you can just add in your tsconfig.json a new field called resolveJsonModule: true, and then you can import all the informations of any .json file just like this:

import * as jsonfile from "./path/to/json"

Upvotes: -2

som
som

Reputation: 2477

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

Upvotes: 10

serkan
serkan

Reputation: 7151

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

Upvotes: 70

Related Questions