JSON.parse("{\"error\":\"Sorry, that is an invalid URL\"}")["error"]
# => "Sorry, that is an invalid URL"
# or
JSON.parse("{\"error\":\"Sorry, that is an invalid URL\"}").fetch("error")
# => "Sorry, that is an invalid URL"
page.body = "{\"error\":\"Sorry, that is an invalid URL\"}"
parsed_body = JSON[page.body, symbolize_names: true]
parsed_body[:error] # => "Sorry, that is an invalid URL"
3条答案
按热度按时间jckbn6z71#
你需要解析json,对它进行散列,然后你可以像这样检查key是否存在:
要获取错误值,方法几乎相同:
oxf4rvwz2#
String#[]
不接受符号参数,这就是为什么你有错误你需要先把字符串转换成哈希,你可以用
JSON::[]
来做。qmelpv7a3#
如果没有错误,返回您想要的内容