Skip to content
← Back to Community
How do I get data from the stuff.json file in javascript
Profile icon
ike_fite

I don't know if I can elaborate further

Voters
Profile icon
ObiVibKenobi
Profile icon
ike_fite
Comments
hotnewtop
Profile icon
RayhanADev

Heya @ike_fite

To read data, you should use the fs node module.

fs.readFileSync( path, options )

the return value will be the content of the file, which in your case is JSON so then you would parse the data

JSON.parse(data)

and then that should be it. Cheers!
~ Ray <3

Profile icon
RayhanADev

So you final code might look like:

let data = JSON.parse(fs.readFileSync([/path-to-file])) console.log(data);

Hope it helps!

Profile icon
realTronsi

@RayhanADev this is the only good answer, everyone else copied @Coder100 dubious answer. Anyways I prefer using readFile() in general cases tbh and just run the rest through the callback, but make sure to set the encoding to 'utf-8' or it will read as a buffer (which I'm assuming he wants it as utf-8)

Profile icon
RayhanADev

@realTronsi lmao your right xD. I like redfilesync more idk why tho.

Profile icon
ike_fite

This community is hands down the best coding comunity. But I probably should have elaboraded. I need the JSON file in the scripts.js file not the index.js file. Im sorry :(

Profile icon
ObiVibKenobi

Require

First Step

First, you need to require it.
const stuff = require(‘./stuff.json’)
I can see you already did that, though...

Using the data

There’s two ways to go here. Say you want to console.log the key from stuff.json
const key = require(‘./stuff.json’)
console.log(key)
Or....
console.log(stuff.key)

Profile icon
RYANTADIPARTHI

require

You have to require that file name

const data = require('./stu..json') fs.writeFileSync(file, value); // then write it out.
Profile icon
Coder100

You can just require it!

const data = require("./stuff.json")

Do note you won't be able to write to it. To write to it, we can use a new function:

function writeToJson(file, value) { const fs = require("fs"); fs.writeFileSync(file, value); }