Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby hash to javascript hash

I have a ruby hash that i want to convert into a specific javascript hash.
Here is the ruby hash keyval

{    
   "Former Administration / Neutral"=>24,     
   "Media Personality / P"=>2,     
   "Journalist / Neutral"=>32,   
   "Consultant / Neutral"=>2,

   ...     

   "Journalist / P"=>11, 
   "Expert / Neutral"=>1, 
   "Activist / Neutral"=>15 
}    

Into javascript hash

{data: "Former Administration / Neutral", frequency: (24) },
{data: "Media Personality / P", frequency: (2) },
{data: "Journalist / Neutral", frequency: (32) },
{data: "Consultant / Neutral", frequency: (2) },

 ...

{data: "Journalist / P", frequency: (11) },
{data: "Expert / Neutral", frequency: (1) },
{data: "Activist / Neutral", frequency: (15) }   

Tried

var obj = {};
for (var i = 0; i < <%= keyval.size %>; i++) {
obj["data"] = <%= keyval.keys[i] %>;
obj["frequency"] = '(' + <%= @keyval.values[i] %> + ')';
}

But the loop is not working obj return the first element of the ruby hash frequency=24 and does not escape the space in Former Administration. Why?

like image 564
mamesaye Avatar asked Feb 06 '14 14:02

mamesaye


1 Answers

There's a to_json method for converting ruby hashes and arrays into json objects. You could make an array of hashes using the first hash, then call to_json on it. Then, you're doing all your data manipulation in ruby, and just converting the format to json at the end.

hash = {    
   "Former Administration / Neutral"=>24,     
   "Media Personality / P"=>2,     
   "Journalist / Neutral"=>32,   
   "Consultant / Neutral"=>2,
   "Journalist / P"=>11, 
   "Expert / Neutral"=>1, 
   "Activist / Neutral"=>15 
}   
arr = []
hash1.each do |k,v|
  arr << {:data => k, :frequency => v}
end
arr.to_json

gives

"[{"data":"Journalist / P","frequency":11},{"data":"Activist / Neutral","frequency":15},{"data":"Former Administration / Neutral","frequency":24},{"data":"Expert / Neutral","frequency":1},{"data":"Journalist / Neutral","frequency":32},{"data":"Consultant / Neutral","frequency":2},{"data":"Media Personality / P","frequency":2}]"

You said that you wanted a "javascript hash", but what it looks like you have in your question, at the end, is an array without the square brackets. My result is a valid json object representation which is an array of objects. Which i think is actually what you want.

like image 177
Max Williams Avatar answered Oct 05 '22 16:10

Max Williams