Come convertire JSON in un hash Ruby


137

Ho un oggetto JSON con il seguente valore:

@value = {"val":"test","val1":"test1","val2":"test2"}

Voglio fare un giro in Ruby per ottenere le coppie chiave / valore. Quando lo uso @each, non scorre attraverso l'oggetto perché non è nella forma hash Ruby:

@value = {"val"=>"test","val1"=>"test1","val2"=>"test2"}

Come posso convertire l'oggetto JSON sopra in un hash Ruby?

Risposte:


250

Che dire del seguente frammento?

require 'json'
value = '{"val":"test","val1":"test1","val2":"test2"}'
puts JSON.parse(value) # => {"val"=>"test","val1"=>"test1","val2"=>"test2"}

7
value = '{"val":"test","val1":"test1","val2":"test2"}'avrebbe potuto essere più leggibile.
luckykrrish,

40

Puoi anche usare il with_indifferent_accessmetodo di Rails in modo da poter accedere al corpo con simboli o stringhe.

value = '{"val":"test","val1":"test1","val2":"test2"}'
json = JSON.parse(value).with_indifferent_access

poi

json[:val] #=> "test"

json["val"] #=> "test"

Qualcuno sa se questo richiede più risorse per gli oggetti hash più grandi? Sono nuovo di Ruby / Rails, ma supponendo che questo duplica coppie chiave-valore?
Jonathan,

4

Supponendo che tu abbia un hash JSON in giro da qualche parte, per convertirlo automaticamente in qualcosa come la versione di WarHog, avvolgi i contenuti dell'hash JSON nei %q{hsh}tag.

Questo sembra aggiungere automaticamente tutto il testo di escape necessario come nella risposta di WarHog.



1

Sono sorpreso che nessuno abbia sottolineato il []metodo JSON , che rende molto semplice e trasparente la decodifica e la codifica da / a JSON.

Se l'oggetto è simile a una stringa, analizza la stringa e restituisce il risultato analizzato come struttura dati Ruby. In caso contrario, generare un testo JSON dall'oggetto struttura dati Ruby e restituirlo.

Considera questo:

require 'json'

hash = {"val":"test","val1":"test1","val2":"test2"} # => {:val=>"test", :val1=>"test1", :val2=>"test2"}
str = JSON[hash] # => "{\"val\":\"test\",\"val1\":\"test1\",\"val2\":\"test2\"}"

strora contiene il codice JSON codificato hash.

È facile invertirlo usando:

JSON[str] # => {"val"=>"test", "val1"=>"test1", "val2"=>"test2"}

Gli oggetti personalizzati devono essere to_sdefiniti per la classe e al suo interno convertire l'oggetto in un hash quindi utilizzarlo to_json.


0

Puoi usare la gemma nice_hash: https://github.com/MarioRuiz/nice_hash

require 'nice_hash'
my_string = '{"val":"test","val1":"test1","val2":"test2"}'

# on my_hash will have the json as a hash, even when nested with arrays
my_hash = my_string.json

# you can filter and get what you want even when nested with arrays
vals = my_string.json(:val1, :val2)

# even you can access the keys like this:
puts my_hash._val1
puts my_hash.val1
puts my_hash[:val1]
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.