json - 将字符串转换为 JSON 导致问题

标签 json node.js

我正在从未正确配置的 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/

相关文章:

javascript - 数据和时间中缺少前导 0

javascript - 使用 Handlebars 生成 JSON

javascript - 为导入的 CSS 文件添加前缀

javascript - NodeJS 异步库并行方法奇怪的行为

javascript - Node js 返回语法错误 : Unexpected identifier

jquery - JQGrid-无法调用ASP.NET WebMethod,但可以使用Ajax

java - Java 序列化、JSON、JAXB 之间的区别?

c# - 是否有从 JSON Web 服务返回错误状态的传统方法?

node.js - 如何记住客户的数据?

node.js - 无法在 Ubuntu 中安装 karma