3

I'm requesting data from an api that isn't configured properly.

It serves as text/html, but when I run JSON.parse(data) I get an parse error. and I do data.trade it says undefined.

If I just echo the data it looks like this (sample, not the full object):

"{\"buyOrder\":[{\"price\":\"5080.000000\"}]}"

Here is the url in question: http://www.btc38.com/trade/getTradeList.php?coinname=BTC

I'm using request module to fetch the data.

How would I convert this string into a JSON object?

Here is the request:

var url = 'http://www.btc38.com/trade/getTradeList.php?coinname=BTC'
, json = true;

request.get({ url: url, json: json, strictSSL: false, headers: { 'User-Agent' : 'request x.y' } }, function (err, resp, data) {
   c.log(data.trade); //undefined
});
whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
chovy
  • 72,281
  • 52
  • 227
  • 295
  • There is no `trade` property in your `data`, that is why `data.trade` is undefined. – zavg Dec 15 '13 at 07:48
  • What code exactly are you using to fetch and parse the data? The endpoint you linked to contains the full JSON output, so I suspect the issue is elsewhere. – Michelle Tilley Dec 15 '13 at 07:50

2 Answers2

4

Trimming the string got everything working well for me:

var request = require('request');

options = {
  url: 'http://www.btc38.com/trade/getTradeList.php?coinname=BTC',
  headers: {
    'User-Agent': 'request x.y'
  }
};

request(options, function(error, response, body) {
  var cleaned = body.trim();
  var json = JSON.parse(cleaned);
  console.log(json.trade);
});

Output (truncated):

[ { price: '5069.000000',
    volume: '0.494900',
    time: '2013-12-15 16:05:44',
    type: '2' },
  { price: '5069.000000',
    volume: '0.230497',
    time: '2013-12-15 16:02:37',
    type: '2' },
  { price: '5100.000000',
    volume: '0.058963',
    time: '2013-12-15 15:58:27',
    type: '1' },
  { price: '5100.000000',
    volume: '0.099900',
    time: '2013-12-15 15:58:27',
    type: '1' },
  { price: '5099.000000',
    volume: '0.344058',
    time: '2013-12-15 15:56:58',
    type: '1' },
  { price: '5069.000000',
    volume: '0.027464',
    time: '2013-12-15 15:55:35',
    type: '2' } ... ]
Michelle Tilley
  • 157,729
  • 40
  • 374
  • 311
0

Without seeing more of your code I won't be able to tell what's wrong, but I would suggest you use the request-json (npm install request-json) package for something like this.

I just ran the following in Node and got a response:

var request = require('request-json');
var client = request.newClient('http://www.btc38.com');
client.get('/trade/getTradeList.php?coinname=BTC', function(err,res,body) { 
    // body is a JSON object
    return console.log(body); 
});
rossipedia
  • 56,800
  • 10
  • 90
  • 93
  • that was just a paste error. the string is much larger. You can see it from the url I provided. – chovy Dec 15 '13 at 07:52