【问题标题】:Ruby JSON returns fine but crashes on ParseRuby JSON 返回正常但在 Parse 上崩溃
【发布时间】:2015-11-17 02:40:21
【问题描述】:

我正在尝试解析从我正在处理的 API 返回的 JSON。我得到的回应是

puts res.body
{"error"=>true, "message"=>"Login failed. Incorrect credentials"}

但如果我尝试使用 JSON 解析它,它会崩溃。

   connection = Connection.new
   res = connection.post("login", {'email':'test@email.com', 'password': 'somepass'})
   puts JSON.parse(res.body)
   puts res.code
   puts res.body

我也试过了,但什么也没返回

puts res["error"]
puts res[0]

【问题讨论】:

    标签: ruby json parsing


    【解决方案1】:

    通过调用 res.to_json 将您的 res 哈希对象转换为 JSON 对象。然后您就可以在该对象上调用JSON.parse,如下所示:

    res = connection.post("login", { 'email': 'test@email.com', 'password': 'somepass' })
    result = JSON.parse(res.to_json)
    # => {"error"=>true, "message"=>"Login failed. Incorrect credentials"}
    result['error']
    # => true
    result['message']
    # => "Login failed. Incorrect credentials"
    

    【讨论】:

    • 感谢 K M Rakibul Islam,你能告诉我为什么我在 JSON.parse 中有 .to_json 吗?
    • 因为,您需要使用 to_json 调用将哈希转换为 json,以便使用 JSON.parse 方法解析 json。否则,您的程序将崩溃并显示以下错误消息:TypeError: no implicit conversion of Hash into String
    • 啊,所以即使使用 JSON.parse 它仍然是一个哈希。感谢您的帮助。
    • 是的,只是等待接受计时器允许我 :)
    猜你喜欢
    • 2011-11-22
    • 1970-01-01
    • 1970-01-01
    • 2016-07-07
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多