需要帮助将单个JSON数据打印到命令行

时间:2016-09-14 15:34:56

标签: express

我目前正在使用MEAN堆栈构建一个完整堆栈的网站。我有一个控制台记录第一个标题的问题,即“星际迷航:电影”和#34;。我能够解析JSON,但我无法获得JSON文件中的第一个标题出现在我的命令行中。 这是下面的JSON文件

 {"data":[
 {
"title":"Star Trek: The Motion Picture",
"imageURL":"https://upload.wikimedia.org/wikipedia/en/d/df/Star_Trek_The_Motion_Picture_poster.png"
},
{
  "title":"Star Trek: The Wrath of Khan",
  "imageURL":"https://upload.wikimedia.org/wikipedia/en/9/9a/Star_Trek_II_The_Wrath_of_Khan.png"
},
{
  "title":"Star Trek III:The Search For Spock",
  "imageURL":"https://upload.wikimedia.org/wikipedia/en/b/b6/Star_Trek_III_The_Search_for_Spock.png"
},
{
  "title":"Star Trek IV:The Voyage Home",
    "imageURL":"https://upload.wikimedia.org/wikipedia/en/6/68/Star_Trek_IV_The_Voyage_Home.png"
},
{
  "title":"Star Trek V: The Final Frontier",
  "imageURL":"https://upload.wikimedia.org/wikipedia/en/7/7c/Star_Trek_V_The_Final_Frontier.png"
},
{
  "title":"Star Trek VI: The Undiscovered Country",
      "imageURL":"https://upload.wikimedia.org/wikipedia/en/f/fa/Star_Trek_VI-poster.png"
}

]}

此外,我的服务器文件使用express js

运行
var express=require('express');
var path=require('path');
var mongoose=require('mongoose');
var body_parser=require('body-parser');
var fs= require('fs');
//var confog=require('./data.json');
var app=express();

app.set('use engine','ejs');



var headerText="";
var subText="";
var odj="";
mongoose.connect('mongodb://localhost/starTrekData');

fs.readFile('data.json','utf8',function(err,data){
  if(err) throw err;
  console.log(JSON.parse(data));
  console.log(data.title);
 });


app.use(express.static(__dirname+'/public'));
app.use(express.static('render'));





app.get('/',function(req,res){
  headerText="Star Trek Movies";
  res.render('render/index.ejs',{opening:headerText});
});
app.get('/home',function(req,res){
  headerText="Star Trek Movies";
  res.render('render/index.ejs',{opening:headerText});
});
//Tells about the creator of the website which is me...
app.get('/about',function(req,res){

 var name="About me";
 res.render('render/about.ejs',{title:name});
});
app.get("/contact",function(req,res){
  headerText="Contact Me";
  res.render("render/contact.ejs",{title:headerText});
});

app.listen(3000,function(){
  console.log("Its listening on 3000");
});

1 个答案:

答案 0 :(得分:0)

如果您想访问文件中的第一个标题,那么您必须这样写: console.log(JSON.parse(data).data[0].title);

也许为了更好的阅读而写一点点不同,如:

var myData = JSON.parse(data);
var title = myData.data[0].title;
console.log(title);

说明:

相关问题