Search code examples
rubydashing

Using map to format JSON


I'm somewhat new to Ruby and I'm working on a dashboard application using Dashing.io and I have some JSON data that, after doing JSON.parse on it, currently looks like this:

{"location"=>"Madison Central", "Members"=>{"Mike"=>"Minecraft crafting", "Dave"=>"3D printing"}}

What I need to do now is to map the content in "Members" so that it looks like the following:

{:label => "Mike", :value=> "Minecraft crafting"}
{:label => "Dave", :value=> "3D printing"}

I tried using map as follows:

event_data = response.map{|who,status| {label: who, value: status} }

but it outputs (predictably) wrongly:

{:label=>"location", :value=>"Madison Central"}
{:label=>"Members", :value=>{"Mike"=>"Minecraft crafting", "Dave"=>"3D printing"}}

How to I get to just what I need in the "Members" array in the JSON?


Solution

  • You need to pull the "Members" out of the hash first

    event_data = response["Members"].map{ |who, status| {label: who, value: status }}