Retrieving JSON values

I’m trying to learn how to use a JSON file to hold information and I don’t know how to retrieve the values from it. Example:
(package.json)

{
   "name":"Codecademy",
   "user":"me",
   "language":"JSON"
}

How would I retrieve these values from package.json?

i believe you can access the information within by utilizing the JSON.parse() function, an example would be something like this

let obj = JSON.parse(‘{
“name”:“Codecademy”,
“user”:“me”,
“language”:“JSON”
}’)

you can than call the different values like this obj.name, obj.user, obj.language. i am not sure if that is 100% what you are looking for but that is one method to utilize json data in a javascript file.

can I do that without typing all of the info out? thanks!

you could use the fetch method, it would look something like this

async function loadTest() {
const response = await fetch(‘/api/test’);
const test = await response.json();

console.log(test.name, test.user, test.language);
//logs Codecademy, me, JSON
}

loadTest();

essentially you can use fetch to retrieve the json data from the url and than manipulate it using the variable that you store the response in just like the previous example i showed you, you stated however you are trying to read from a package.json file, the approach above is for json data stored in external servers, if you are trying to extract the values locally you can do something like this

const data = require(‘./package.json’);
console.log(data.name, data.user, data.language); these answers are based off the assumption you are using node.js if you are using something else some slight adjustments will need to be made, let me know if you are using something different.

that’s perfect, thank you!!

1 Like