converting string to JSON causing problems (Node.Js & request module)

1.7k views Asked by At

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
});
2

There are 2 answers

4
Michelle Tilley On BEST ANSWER

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' } ... ]
1
rossipedia On

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); 
});