简体   繁体   中英

Transforming JSON to nested ruby hash

I have a JSON block that I want to convert to a ruby hash.

json_blob = {"WHATEVER"=>{"FOO"=>"BAR", "CAT"=>"DAY}}

so that when I am using the data, I can check whether the data is there. Example:

hashed_json_blob[:whatever][:foo] returns "bar"

and also, I could handle values that don't exist either (they were omitted in the json_blob).

hashed_json_blob[:whatever][:nonexistant] returns nil

Note: if there is an easier way with the data as XML, that can work to. The json_blob was pulled using JSON.parse

your json_blob object is already a hash (minus one missing quote at the end of "DAY"):

json_blob = {"WHATEVER"=>{"FOO"=>"BAR", "CAT"=>"DAY"}}

with this you can do:

json_blob["WHATEVER"]
=> {"FOO"=>"BAR", "CAT"=>"DAY"}

json_blob["WHATEVER"]["FOO"]
=> "BAR"

The same data as a json object would look like this:

{"WHATEVER":{"FOO":"BAR","CAT":"DAY"}}

gem install json

require 'json'

json_blob = {"WHATEVER"=>{"FOO"=>"BAR", "CAT"=>"DAY}}

abc = JSON.parse(json_blob)

现在您可以对abc执行操作

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM