Skip to content

Instantly share code, notes, and snippets.

@tmbritton
Created January 28, 2014 05:35
Show Gist options
  • Save tmbritton/8662754 to your computer and use it in GitHub Desktop.
Save tmbritton/8662754 to your computer and use it in GitHub Desktop.
Grab JSON from mtgjson.com, parse it and write out simplified json file of just card id and title.
/**
* @file
* Fetch card data from mtgjson.com, write it in a format
* that is more easily consumed by our application.
*/
'use strict';
var http = require('http'),
fs = require('fs');
var fetchData = {
//Properties
properties: {
url: 'http://mtgjson.com/json/AllSets-x.json'
},
/**
* Get the JSON file.
*/
getJson: function (url) {
//console.log(url);
http.get(url, function (res) {
var str = '';
console.log('Response: ' + res.statusCode);
res.on('data', function (chunk) {
str += chunk;
});
res.on('end', function () {
fetchData.parseJson(str);
});
}).on('error', function (e) {
console.log("Error: " + e.message);
});
},
/**
* Kick it off.
*/
init: function () {
fetchData.getJson(fetchData.properties.url);
},
/**
* Read the JSON response.
*/
parseJson: function (jsonString) {
var cards = {},
card = {},
set = {},
cardObj = {},
jsonObj = JSON.parse(jsonString);
for (set in jsonObj) {
if (jsonObj.hasOwnProperty(set)) {
for (card in jsonObj[set].cards) {
if (jsonObj[set].cards.hasOwnProperty(card)) {
cardObj = jsonObj[set].cards[card];
cards[cardObj.multiverseid] = {};
cards[cardObj.multiverseid].id = cardObj.multiverseid;
cards[cardObj.multiverseid].name = cardObj.name;
}
}
}
}
fetchData.writeFile(cards);
},
/**
* Write JSON data to file.
*/
writeFile: function (json) {
var jsonString = JSON.stringify(json);
fs.writeFile('./carddata.json', jsonString, function (err) {
if (err) {
console.log(err);
} else {
console.log('Card Data Saved');
}
});
}
};
fetchData.init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment