简体   繁体   中英

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?

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.

You can dothis using map and join

keyval.map{|k,v| "{data: \"#{k}\", frequency: (#{v}) }" }.join(",\r\n")

the map method provides the key as k and the value as v in this example.

Try this:

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

So you will get an array of those objects.

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