Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading JSON properties in NodeJS?

I'm having trouble reading properties from JSON within NodeJS.

Feels like an obvious mistake I may be making..

The JSON is from this endpoint;

http://hypem.com/playlist/history/faisdotal/json/1/data.js

My code:

var request = require('request');

request("http://hypem.com/playlist/history/faisdotal/json/1/data.js", function (err, res, json) {
  JSON.parse(json);
  console.log(json["1"]["artist"]);  // undefined
});

~

like image 769
faiizow Avatar asked Nov 26 '25 19:11

faiizow


2 Answers

You need to store the returned value of JSON.parse:

json = JSON.parse(json);
console.log(json["1"]["artist"]);
like image 170
Dennis Avatar answered Nov 29 '25 09:11

Dennis


I think you want:

json = JSON.parse(json);

It won't (and can't) simply update the value of the parameter. The .parse() routine returns the value parsed from the string you pass it.

JavaScript is purely call-by-value, so there's really no way it could possibly work the way your code is written.

like image 30
Pointy Avatar answered Nov 29 '25 10:11

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!