Cyrus Zei Cyrus Zei - 7 months ago 20
Javascript Question

render json data in index

I dont understand why this is not working. Sometimes I can get the first object from the json file and as soon as i want a nested object it fails to fetch it.

How do i make it render the "album_cover" text ?

I am using express js.

my index.js in routing folder

var express = require('express');

var router = express.Router();

var fs = require('fs');



/* GET home page. */

router.get('/', function(req, res, next) {

var file = __dirname + '/../public/list/list.json';


fs.readFile(file, 'utf8', function (err, data) {

if (err) {

console.log('Error: ' + err);

return;

}


data = JSON.parse(data);

console.log(data);

res.render('index', { title: data });

});

});


module.exports = router;


and here is my json file.

{
"Year": {
"2011": {
"top40": {
"id": {
"01": {
"album_cover": "http://o.scdn.co/image/830a22646bc38f72df95ec98e3ab6bb19aa6074b",
"artist namn": "Adele",
"song": "Rolling In The Deep",
"spotify": "http://open.spotify.com/track/7h8Ud480Fm4ReUVxgFF9ZX",
"youtube": "http://youtu.be/rYEDA3JcQqw"
},
"02": {
"album_cover": "http://o.scdn.co/image/215c999786e8319a09b7af87a970c2bdb6747c92",
"artist namn": "LMFAO",
"song": "Party Rock Anthem",
"spotify": "http://open.spotify.com/track/1CNJyTUh56oj3OCZOZ5way",
"youtube": "http://youtu.be/KQ6zr6kCPj8"
}
}
}
}
}
}


and here is my index view file

<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>

<h1>Top Hits year : :<%= title %></h1>
<h2>Adele<%= title %></h2>
<p>Rolling In The Deep <%= title %></p>
<a href="http://open.spotify.com/track/7h8Ud480Fm4ReUVxgFF9ZX " target="_blank"><img src="/images/spotify.jpg"></a>
<a href="http://youtu.be/rYEDA3JcQqw" target="_blank"><img src="/images/youtube.png"></a>
</body>
</html>

Answer

When I converted your object it gives me an error at "2011" because it is a number.

console.log(data.Year.2011);

I changed your json like

{
  "Year": {
    "top2011": {
      "top40": {
        "id": {
          "top01": {
            "album_cover": "http://o.scdn.co/image/830a22646bc38f72df95ec98e3ab6bb19aa6074b",
        "artist namn": "Adele",
        "song": "Rolling In The Deep",
        "spotify": "http://open.spotify.com/track/7h8Ud480Fm4ReUVxgFF9ZX",
        "youtube": "http://youtu.be/rYEDA3JcQqw"
      },
      "top02": {
        "album_cover": "http://o.scdn.co/image/215c999786e8319a09b7af87a970c2bdb6747c92",
        "artist namn": "LMFAO",
        "song": "Party Rock Anthem",
        "spotify": "http://open.spotify.com/track/1CNJyTUh56oj3OCZOZ5way",
        "youtube": "http://youtu.be/KQ6zr6kCPj8"
      }
     }
    }
   }
  }
 }

After this I am able to use it

console.log(data.Year.top2011.top40.id.top01.album_cover);

OR without changing your json you can use like

data.Year['2011']['top40']['id']['01']['album_cover']);

or

data.Year['2011'].top40.id['01'].album_cover
Comments