我正在从未正确配置的 API 请求数据。
它用作文本/html,但是当我运行 JSON.parse(data) 时,我得到一个解析错误。我做 data.trade
它说未定义。
如果我只是回显数据,它看起来像这样(样本,而不是完整的对象):
"{\"buyOrder\":[{\"price\":\"5080.000000\"}]}"
这是有问题的网址: http://www.btc38.com/trade/getTradeList.php?coinname=BTC
我正在使用 request
模块来获取数据。
如何将此字符串转换为 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 x.y' } }, function (err, resp, data) {
c.log(data.trade); //undefined
});
最佳答案
修剪绳子让一切对我来说都很好:
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);
});
输出(截断):
[ { 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' } ... ]
关于json - 将字符串转换为 JSON 导致问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20592357/