Skip to content
Advertisement

How to read specific object from json file in JavaScript?

I’m trying to work with a json file but I can’t figure out how to read just a specific object from a json file.

My current code looks like this:

try {
    const data = fs.readFileSync("addresses.json", "utf8");
    console.log(data);
} catch (err) {
    console.error(err);
}

This works fine. However when I try to get some object from the file like this:

console.log(data.address)

It doesn’t work because it is a string.

So my question is how can I read just a single object from the json file.

Thanks a lot!

Advertisement

Answer

Try:

const parsedData = JSON.parse(data)
const address = parsedData.address
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement