Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

extracting JSON name of a hash

The following segment of a JSON file needs to be transformed, essentially flattening it to a single hash for sizes

    "sizes" : {
      "small" : {
        "w" : "680",
        "h" : "261",
      },
      "large" : {
        "w" : "878",
         "h" : "337",
      },
      "medium" : {
        "w" : "878",
        "h" : "337",
      }

while the child attributes are accessible as:

 parent['sizes'].each do |size|
   w: size['w'],
   h: size['h'],
   label: size
 end

will not function, as the whole hash will be loaded for the label. How can the hash’s identity string only be captured?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For hashes each calls the block once for each key in hash, passing the key-value pair as parameters.

Like this:

parent['sizes'].each do |key, size|
  # format your preferred output here
  # key is small, large, medium
  # and size is {"w"=>"680", "h"=>"261"}, ...
  # for example
  {
    w: size['w'],
    h: size['h'],
    label: key
  }
end
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading