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
});
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' } ... ]