2017-06-10 9 views
0

JS経由でGETリクエストをhttps://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=API-KEY-HEREに送信しています。しかし、私はポップアップする長いJSONをどのように解析するのか全く考えていません。私は最初の記事のタイトルを取得したい。Javascript - 長いGETリクエストの解析JSON

コード:

var HttpClient = function() { 
    this.get = function (aUrl, aCallback) { 
     var anHttpRequest = new XMLHttpRequest(); 
     anHttpRequest.onreadystatechange = function() { 
      if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200) 
       aCallback(anHttpRequest.responseText); 
     } 

     anHttpRequest.open("GET", aUrl, true); 
     anHttpRequest.send(null); 
    } 
} 
var client = new HttpClient(); 
client.get('https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=08f3b70e722d46ebab1fdd5b5499f671', function (response) { 
    console.log(response); 
}); 

編集:私はconsole.log(response['articles'][0]);を使用してみましたが、それは私が持っていないエラー

+0

@Patrickありませんが返されます。しかし私はJSを使用していません.NET –

+0

それは何のエラーを返しますか? – Patrick

+0

@Patrick '' 'Uncaught TypeError:未定義の' 0 'のプロパティを読み取れません。 –

答えて

1

使用JSON.parse

var client = new HttpClient(); 
client.get('https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=<your-api-key-here>', function (response) { 
    var json = JSON.parse(response); 

    console.log(json['articles'][0]); 
}); 
+0

ありがとうございました!私はこの答えを選択するのを待たなければならない –