2016-09-14 6 views
0

私は現在、平均スタックを使用してフルスタックのウェブサイトを構築しています。私は最初のタイトルである「Star Trek:The Motion Picture」をコンソールに記録することに問題があります。私は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" 
} 

]} 

以下のJSONファイルは私のサーバーのファイルが明示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"); 
}); 

答えて

0

を実行していますその: console.log(JSON.parse(data).data[0].title);

たぶんのような、より良い読書のために少し異なるそれを書く:

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

説明:

  • JSON.parse(data) - >は、JSONオブジェクトに、あなたの文字列に変換します。それはあなたの実際のプロパティだから> - データが配列され、あなたが最初のインデックスに
  • titleにアクセスしたいので> - あなたが検索要素は、このオブジェクト
  • [0]であるため、> - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
  • dataを参照してください。私が理解できる限りアクセスしたい
関連する問題