【问题标题】:Can't access parsed JSON in Coffeescript with Hubot无法使用 Hubot 在 Coffeescript 中访问解析的 JSON
【发布时间】:2016-08-27 18:16:17
【问题描述】:

我正在使用hubot 为我公司的Rocket Chat 服务器编写脚本。作为一个学习步骤,我决定尝试从 forecast.io 获取 API 数据并将某些成员输出给用户。但是,无论我尝试什么,我的机器人都不会输出 JSON。当我尝试发送整个正文时,它只显示“[object Object]”,而当我尝试输出某些成员时,它要么发送“未定义”,要么根本不发送任何内容。另外,我尝试过使用“json['member']['member']”和“json.member.member”之类的语法(我在互联网上都看到过),但都没有奏效。任何帮助是极大的赞赏。提前致谢。 (注意:我没有包含在代码中作为 FORECAST_KEY 编写的 API 密钥)

已解决: 我不完全理解 node.js 的全部内容。 Node.js 是基于事件的,这意味着它会在事件发生时执行操作,而不是按线性顺序执行操作。

我的问题是数据返回和函数返回之间存在延迟。更简单地说,直到函数已经返回空容器之后,请求才完成。问题在于我使用单独的函数,而不是直接在代码中包含请求。

module.exports = (robot) ->
    robot.hear /weather/i, (res) ->
        testurl = "https://api.forecast.io/forecast/#{FORECAST_KEY}/37,-10"
        data = httpRequest(robot, testurl, res)
        res.send("Checking Weather...")
        res.send("#{data['latitude']}")
        res.send("#{data.latitude}")

httpRequest = (robot, url, topRes) ->
    topRes.http(url)
        .get() (err, res, body) ->
            #If error, display error
            if err
                topRes.send("Bot Encountered an Error :: #{err}")
            else
                #Try to parse JSON
                tryBody = body
                try
                    data = JSON.parse(tryBody)
                catch e
                    #Catch error, return plain body
                    return body
                #If not error, return JSON
                return data

【问题讨论】:

  • 你还有这个问题还是解决了。您可以使用简单的JSON.stringify body 来查看原始 json。

标签: json coffeescript hubot


【解决方案1】:

您是否尝试在 httpRequest 函数中添加日志语句? httpRequest 是一个命名函数,必须在调用它之前声明。

将代码改为:

httpRequest = (robot, url, topRes) ->
  topRes.http(url)
    .get() (err, res, body) ->
        #If error, display error
        if err
            topRes.send("Bot Encountered an Error :: #{err}")
        else
            #Try to parse JSON
            tryBody = body
            try
                data = JSON.parse(tryBody)
            catch e
                #Catch error, return plain body
                return body
            #If not error, return JSON
            return data

module.exports = (robot) ->
  robot.hear /weather/i, (res) ->
    testurl = "https://api.forecast.io/forecast/#{FORECAST_KEY}/37,-10"
    data = httpRequest(robot, testurl, res)
    res.send("Checking Weather...")
    res.send("#{data['latitude']}")
    res.send("#{data.latitude}")

参考:https://softwareengineering.stackexchange.com/questions/191196/coffeescript-and-named-functions

希望这会有所帮助。

谢谢, 帕尼。

【讨论】:

    猜你喜欢
    • 2018-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 2012-04-23
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多