将string转换为JSON导致问题
我正在从一个没有正确configuration的api请求数据。
它作为文本/ HTML,但是当我运行JSON.parse(数据)时,我得到一个parsing错误。 我做data.trade
它说未定义。
如果我只是回显数据,它看起来像这样(样本,而不是完整的对象):
"{\"buyOrder\":[{\"price\":\"5080.000000\"}]}"
这里是有问题的url: http ://www.btc38.com/trade/getTradeList.php?coinname =BTC
我正在使用request
模块来获取数据。
我将如何将此string转换为JSON对象?
这是请求:
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 xy' } }, function (err, resp, data) { c.log(data.trade); //undefined });
修剪string得到了一切为我工作的好:
var request = require('request'); options = { url: 'http://www.btc38.com/trade/getTradeList.php?coinname=BTC', headers: { 'User-Agent': 'request xy' } }; request(options, function(error, response, body) { var cleaned = body.trim(); var json = JSON.parse(cleaned); console.log(json.trade); });
输出(截断):
[ { 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' } ... ]
没有看到更多的代码,我将无法辨别出什么问题,但是我build议你使用request-json
( npm install request-json
)包。
我刚刚在Node中运行以下代码,得到了一个响应:
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); });