2016-11-15 5 views
0
require 'json' 
begin 
    hash = {"a" => "b"} 
    raise StandardError, hash 
rescue Exception => e 
    q = e.message 
    p q 
    p q.to_json 
end 

"{\"a\":\"b\"}"が印刷されますが、"\"{\\\"a\\\"=>\\\"b\\\"}\""が印刷されます。何らかの理由?JSON形式がレスキューブロックに入っていません - ルビー

+2

'p'の代わりに' puts'/'print'を使います。 – mudasobwa

+0

puts/printsは、「{\ "a \":\ "b \"}」ではなく、「 "a" => "b"} "{\" a \ "= \" b \ "}」" – Amith

+0

'require" json ' hash = {"a" => "b"} print hash.to_json'を実行すると、{"a": "b"}が出力されます。私の質問は、これがレスキューブロックに渡されたときに同じものが印刷されない理由です。 – Amith

答えて

3

常に文字列として扱わraiseメソッドの2番目の引数は、あなたが救助からハッシュを持つことができないので、あなたはJSONに変換し、バック

require 'json' 
begin 
    hash = {"a" => "b"} 
    raise StandardError, hash.to_json # to string 
rescue Exception => e 
    q = JSON.parse(e.message)   # from string 
    p q.to_json 
end 
=> "{\"a\":\"b\"}" 

ことができ、私はまたして悪の道を知っていますeval

require 'json' 
begin 
    hash = {"a" => "b"} 
    raise StandardError, hash 
rescue Exception => e 
    q = eval(e.message) 
    p q.to_json 
end 
=> "{\"a\":\"b\"}" 

しかし、それは良くありません。使い方eval本当に本当に悪いです。

+1

なぜJSON.parseではないのですか? – mudasobwa

+1

ハッシュの文字列表現を解析しますか? –

+1

はい、自分でそれを試してください:) – mudasobwa

関連する問題