ChatGPT解决这个技术问题 Extra ChatGPT

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?

See this similar question: stackoverflow.com/questions/4662851/…
@coen What do you mean by "include a JSON file"? Read and parse it? If yes, possible duplicate of: stackoverflow.com/questions/5726729/…
yes; read and parse. But this is specifically reading a file, similar to reading a js file, so this is no duplicate and goatslacker's answer is still valid.

F
Frank Nocke

As of node v0.5.x yes you can require your JSON just as you would require a js file.

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

In ES6:

import someObject from ('./somefile.json')


You need to use require('./somefile.json') assuming the file is in the same directory (note the dot and slash).
There's one gotcha with this. The result will be cached! So if you for some reason need to load the data again (say at a cronjob), you'll get the same old result.
Note : the extension .json seem to matter
well formed json helps too
Just as a note, if you did want a different file other than .json to be parsed as json, you could teach require how to read it. require.extensions['.har'] = require.extensions['.json']; var blar = require('./file.har'); will now be treated as json
s
serkan

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

r
rajmobiapp

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


Note that the fs method uses the directory where node was launched from as a starting point, not the directory where the source code doing the read resides, whereas the "require" method uses the path relative to the importing source code location. So you will have differences in paths between the two methods as soon as you store things in different folders.
R
Raynos

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

Or use an existing library like

cjson

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

module.exports = {
  // json
}

@coen yes, we always use __dirname to make relative paths.
Ran into this where it will import JSON locally but not in the docker container on my EC2 instance in AWS... Instead of trying to configure mime types and what not, I just switched to JS instead of JSON. Hope this may help someone.
s
som

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

d
dreamLo

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


I
Igor Litvinovich

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.


This is confusing. Your proposed example of wanting to change the json require to a js require is a stretch of the imagination. Your answer should just stick to the facts and avoid the hypothetical scenario. I also suggest that your hypothetical filename ./myJsonFile.js is confusing. Why would it be called "myJsonFile" if it has a .js extension? Additional useful fact though: if you do require('./file') and both file.js and file.json exist, then it will use file.js.
T
Thanawat Gulati

You can use a module to create a require.

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

T
Thiago Dantas

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"