2014-08-27 20 views
11

Ho un Hash:Convertire un rubino Hash in JSON (senza caratteri di escape)

my_hash = {"[email protected]"=>{"first"=>"Bob", "last"=>"Johnson"}, "[email protected]"=>{"first"=>"Lisa", "last"=>"Dell"}} 

Quando provo a serializzare con my_hash.to_json questo è ciò che ho:

"{\"[email protected]\":{\"first\":\"Bob\",\"last\":\"Johnson\"},\"[email protected]\":{\"first\":\"Lisa\",\"last\":\"Dell\"}}" 

Come potrei convertire un hash in formato JSON senza ottenere caratteri di escape?

risposta

36

Questi caratteri di escape sfuggono a " in Ruby String (l'output my_hash.to_json). Se lo fai

puts my_hash.to_json 

vedrai che in realtà questi caratteri di escape non vengono aggiunti stringa di output.

+0

Oh capisco, quindi presumo che starò bene con 'my_hash.to_json' nel mio codice? – Numbers

+1

@Numeri si, dovresti essere. –

+1

È necessario richiedere la libreria, è nella libreria standard ruby, non nel core: 'require 'json'' – koffeinfrei

Problemi correlati