LoginSignup
80
84

More than 5 years have passed since last update.

Node.jsでHTTP GETしてJSONパースするメモ

Posted at

あけましておめでとうございます。

Node.js HTTP GETなんか検索したら、自分が学生の時に書いていた記事がヒットして、間違い見つけて修正したかったのでES2015な感じにしつつなメモ。

EXPRESS(NODE.JS)でHTTP.GETでJSONを取得してパースする
↑すでにログイン情報忘れてて修正できない

Node.jsのバージョン

$ node -v
v5.3.0

Qiitaの記事のjsonを取得してパースします。

@kazuhikoyamashitapyenvを利用してPython環境を整備する方法をたまたまタブで開いていたので使ってみます。

Qiitaは記事のURL+.jsonってつけるとjsonを返してくれますね。
http://qiita.com/kazuhikoyamashita/items/273692ccbdf8c0950a71.json

app.js
'use strict'

let http = require('http');
const URL = 'http://qiita.com/kazuhikoyamashita/items/273692ccbdf8c0950a71.json';

http.get(URL, (res) => {
  let body = '';
  res.setEncoding('utf8');

  res.on('data', (chunk) => {
      body += chunk;
  });

  res.on('end', (res) => {
      res = JSON.parse(body);
      console.log(res);
  });
}).on('error', (e) => {
  console.log(e.message); //エラー時
});

実行

$ node app.js
{ id: 352559,
  user_id: 41823,
  title: 'pyenvを利用してPython環境を整備する方法',
  raw_body: 'LIGアドベントカレンダー15日目です!こんにちは、Jack (@kazuhikoyamashita) です。\n\n最近の趣味はPythonで行列計算をする事です。\n今回は、pyenvを利用してPython環境を構築する
  ・
  ・
  (省略)
  ・
  ・
  uuid: '273692ccbdf8c0950a71',
  secret: false,
  lang: 0,
  via: 0,
  tweet: false,
  gist: false,
  gist_url: null,
  gist_id: null,
  banned: false,
  created_at: '2015-12-15T00:57:02.000+09:00',
  updated_at: '2015-12-15T06:01:51.000+09:00',
  flags: 0 }

こんな感じでJSONを取得することができました。
ライブラリ依存も無いし最低限のスニペットな感じですね。

80
84
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
80
84