Convertir json en ruby hash


Tengo un objeto JSON con el siguiente valor:

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

Quiero hacer un bucle en Ruby para obtener los pares de valores clave. Cuando uso @each, no itera a través del objeto porque no está en la forma de hash de ruby:

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

¿Cómo puedo convertir el objeto JSON anterior a Ruby hash?

Author: Tot Zam, 2011-11-01

4 answers

¿Qué pasa con el siguiente fragmento?

require 'json'
value = '{"val":"test","val1":"test1","val2":"test2"}'
puts JSON.parse(value) # => {"val"=>"test","val1"=>"test1","val2"=>"test2"}
 216
Author: WarHog,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-05 12:31:33

También puedes usar el método de ruby: with_indifferent_access para que puedas acceder al cuerpo con símbolos o cadenas.

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

Entonces

json[:val] #=> "test"

json["val"] #=> "test"
 12
Author: crims345,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-30 17:42:54

Suponiendo que tenga un hash JSON en algún lugar, para convertirlo automáticamente en algo como la versión de WarHog, envuelva su contenido de hash json en etiquetas %q{hsh}. Esto parece agregar automáticamente todo el texto escapado necesario como en la respuesta de WarHog

 3
Author: boulder_ruby,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-15 21:22:42

¿has probado: http://flori.github.com/json/.

En su defecto, ¿podrías analizarlo? Si solo le interesan los arrays, algo para dividir lo anterior será bastante simple. N

 2
Author: Nick Cartwright,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-01 08:59:57