0

I am accessing cryptsy.com API and return is JSON objects nested within eachother, but I dont understand how to go beyond first level. API method I use is http://pubapi.cryptsy.com/api.php?method=marketdatav2

And my code is

var http = require('http')

http.request({
    host: 'pubapi.cryptsy.com',
    path:'/api.php?method=marketdatav2'
},
    function (res) {
    var body ='';
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        body += chunk;
    });
    res.on('end', function () {
        var obj = JSON.parse(body);

        for(var i in obj) {
            console.log(obj[i]);
        };
    });
}).end()

while output is

localhost:Alts praeconium$ node cryptsy1.js
1
{ markets: 
  { 'ADT/XPM': 
    { marketid: '113',
      label: 'ADT/XPM',
      lasttradeprice: '0.00000316',
      volume: '49270184.97861321',
      lasttradetime: '2014-03-12 18:24:40',
      primaryname: 'AndroidsTokensV2',
      primarycode: 'ADT',
      secondaryname: 'PrimeCoin',
      secondarycode: 'XPM',
      recenttrades: [Object],
      sellorders: [Object],
      buyorders: [Object]
    },
    'ASC/XPM': 
    { marketid: '112',
      label: 'ASC/XPM',
      lasttradeprice: '0.00013982',
      volume: '485160.57447084',
      lasttradetime: '2014-03-12 18:29:07',
      primaryname: 'AsicCoin',
      primarycode: 'ASC',
      secondaryname: 'PrimeCoin',
      secondarycode: 'XPM',
      recenttrades: [Object],
      sellorders: [Object],
      buyorders: [Object] },

I've also tried variation of output function

for(var i in obj.recenttrades) {
    console.log(obj.recenttrades[i]);
};

no output.

Basically, I'd like to parse objects within recenttrades, sellorders, buyorders.. or any object within object. And be able to assign them to a variable, or sdout them with node.js?

Blundering Philosopher
  • 6,245
  • 2
  • 43
  • 59
Velletti
  • 65
  • 1
  • 12

1 Answers1

1

short story

You have an array containing object - therefore the working syntax should be

for(var i in obj.recenttrades[0]) {
    console.log(obj.recenttrades[0][i]);
};

long story

In the JSON you've provided, recenttrades contains array of objects with this syntax:

{
  "id":"29999679",
  "time":"2014-03-12 18:15:36",
  "price":"0.00001669",
  "quantity":"2.16106820",
  "total":"0.00003607"
}

If you get TypeError: Cannot read property '0' of undefined then you iterate wrong object: try to iterate i.e.

obj["return"]["markets"]["ADT\/XPM"]["recenttrades"]

recenttrades are childs of markets childs, which are ADT/XPM, ASC/XPM, COL/XPM etc. in your case the parsing loop would be:

var markets = obj["return"]["markets"];
for(var i in markets) {
  for(var j in markets[i]["recenttrades"]) {
    // iterate the markets[i]["recenttrades"][j] object, see thestructure above
  }
}

Do the same with sellorders and buyorders. I hope we have unweaved the structure well.

Jan Turoň
  • 31,451
  • 23
  • 125
  • 169