I have a JSON object which looks like this:
{ "name":"bacon" "category":["food","meat","good"] "calories":"huge" }
I am trying to flatten that into an array of unique values. I need to build a fact table for Tableau which is not able to work with cross-tabulated data or JSON data directly.
I am not picky about whether I do this in Python or Ruby, but so far I've been trying to do it in Ruby. I am able to easily parse the JSON and get a Ruby hash out of it which seems like the right thing to do first.
{"name"=>"bacon", "category"=>["food", "meat", "good"], "calories" => "huge"}
and I need to produce this:
name,category,calories
bacon,food,huge
bacon,meat,huge
bacon,good,huge
So I think I need to loop through that hash and try to un-nest it. I've been experimenting with something like this:
def Flatten(inHash)
inHash.each do |key,value|
if value.kind_of?(Hash)
Flatten(value)
else
puts "#{value}"
end
end
end
But and that seems to print all of the values, but it doesn't repeat the value that came before. So I get output that looks like
bacon
food
meat
good
huge
Is there a built-in method or gem or library that will this or am I looking at building from scratch? Any ideas on how to get the output that I want? I speak Ruby and Python so if you've got a Python answer please share.