1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Node.js】https.getメソッドでJSONをパースする方法

Posted at

プログラミング勉強日記

2021年3月3日

JSON・JSONパースとは

 JSONはJavaScript Object Notationの略で、色々な情報をやり取りするためのデータ形式で、単純な文字列のサーバー間のデータ通信に最適である。JSONの中身はJavaScriptのオブジェクト形式のような構造をしているので、JavaScriptやNode.jsと相性がいい。

 JSONパースは、JSONデータを解析して使用するということである。

https.getの使い方

 httpsモジュールは、HTTPS通信をNode.jsから簡単に構築できる基本的なモジュールである。

Node.jsでhttps通信を使用できるようにする
var https = require('https');

 JSONでイベント情報を取得できるATND APIを使用して、Node.jsから通信を行う通信を行うURLとhttps.getメソッドを次のように記述する。

// urlにANTDのAPIを設定する
var url = 'https://api.atnd.org/events/?keyword_or=javascript&format=json';

https.get(url, function (res) { });

 基本的には取得したJSONデータは、コールバック関数のresに格納されるので、on()を使って取得する。

var data = [];
 
https.get(url, function (res) {
  // 取得するデータを配列dataに格納する
  res.on('data', function(chunk) {
 
      data.push(chunk);
 
  }).on('end', function() {
 
      var events   = Buffer.concat(data);
      
      console.log(events);
 
  });
});

https.getメソッドでJSONをパースする方法

 取得したJSONデータはそのままだとNode.jsでは扱いにくいデータになっているので、パースする。具体的には、一般的なオブジェクト形式に変換する。そのために、JSON.parse()メソッドを使う。

https.get(url, function (res) {
  res.on('data', function(chunk) {
    data.push(chunk);
  }).on('end', function() {
 
    var events   = Buffer.concat(data);
    // オブジェクト形式に変換する(パースする)
    var r = JSON.parse(events);
 
    console.log(r);
 
  });
});

参考文献

Node.jsでhttps.getしてJSONパースする方法【初心者向け】
【Node.js入門】https.get / requestによるJSONの取得・パース方法まとめ!

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?