Analizar una cadena JSON en Ruby
Tengo una cadena que quiero analizar en Ruby:
string = '{"desc":{"someKey":"someValue","anotherKey":"value"},"main_item":{"stats":{"a":8,"b":12,"c":10}}}'
Hay una manera fácil de extraer los datos?
7 answers
Esto se parece a JavaScript Object Notation (JSON). Puede analizar JSON que reside en alguna variable, por ejemplo json_string
, de la siguiente manera:
require 'json'
JSON.parse(json_string)
Si está utilizando un Ruby anterior, es posible que necesite instalar la gema json .
También hay otras implementaciones de JSON para Ruby que pueden ajustarse mejor a algunos casos de uso:
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
2018-10-03 03:43:24
Solo para extender un poco las respuestas con qué hacer con el objeto analizado:
# JSON Parsing example
require "rubygems"
require "json"
string = '{"desc":{"someKey":"someValue","anotherKey":"value"},"main_item":{"stats":{"a":8,"b":12,"c":10}}}'
parsed = JSON.parse(string) # returns a hash
p parsed["desc"]["someKey"]
p parsed["main_item"]["stats"]["a"]
# Read JSON from a file, iterate over objects
file = open("shops.json")
json = file.read
parsed = JSON.parse(json)
parsed["shop"].each do |shop|
p shop["id"]
end
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
2016-12-12 22:40:47
A partir de Ruby v1.9. 3 no es necesario instalar ninguna Gems para analizar JSON, simplemente use require 'json'
:
require 'json'
json = JSON.parse '{"foo":"bar", "ping":"pong"}'
puts json['foo'] # prints "bar"
Ver JSON en Ruby-Doc.
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
2016-12-12 22:39:25
Parece una cadena JSON. Puedes usar una de las muchas bibliotecas JSON y es tan simple como hacer:
JSON.parse(string)
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
2016-12-12 22:39:49
Esto es un poco tarde, pero me encontré con algo interesante que parece importante contribuir.
Accidentalmente escribí este código, y parece funcionar:
require 'yaml'
CONFIG_FILE = ENV['CONFIG_FILE'] # path to a JSON config file
configs = YAML.load_file("#{CONFIG_FILE}")
puts configs['desc']['someKey']
Me sorprendió ver que funciona ya que estoy usando la biblioteca YAML, pero funciona.
La razón por la que es importante es que yaml
viene incorporado con Ruby, por lo que no hay instalación de gema.
Estoy usando versiones 1.8.x y 1.9.x-así que la biblioteca json
no está incorporada, pero está en la versión 2.x.
Así que técnicamente - esta es la forma más fácil de extraer los datos en la versión inferior a 2.0.
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
2015-11-09 17:43:33
Esos datos parecen estar en formato JSON.
Puede usar esta implementación JSON para Ruby para extraerla.
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-03-23 19:42:03
Sugiero Oj ya que es waaaaaay más rápido que la biblioteca JSON estándar.
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
2015-06-10 02:52:26