ruby hash to javascript hash
发布时间:2020-12-17 03:32:02 所属栏目:百科 来源:网络整理
导读:我有一个 ruby哈希,我想转换成一个特定的 JavaScript哈希. 这是ruby hash keyval { "Former Administration / Neutral"=24,"Media Personality / P"=2,"Journalist / Neutral"=32,"Consultant / Neutral"=2,... "Journalist / P"=11,"Expert / Neutral"=1,"A
我有一个
ruby哈希,我想转换成一个特定的
JavaScript哈希.
这是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 } 进入javascript哈希 {data: "Former Administration / Neutral",frequency: (24) },{data: "Media Personality / P",frequency: (2) },{data: "Journalist / Neutral",frequency: (32) },{data: "Consultant / Neutral",... {data: "Journalist / P",frequency: (11) },{data: "Expert / Neutral",frequency: (1) },{data: "Activist / Neutral",frequency: (15) } 试着 var obj = {}; for (var i = 0; i < <%= keyval.size %>; i++) { obj["data"] = <%= keyval.keys[i] %>; obj["frequency"] = '(' + <%= @keyval.values[i] %> + ')'; } 但循环不工作obj返回ruby散列频率= 24的第一个元素并且不会逃避前管理中的空间.为什么? 解决方法
有一个to_json方法,用于将ruby哈希和数组转换为json对象.您可以使用第一个哈希创建哈希数组,然后在其上调用to_json.然后,你在ruby中进行所有数据操作,最后将格式转换为json.
hash = { "Former Administration / Neutral"=>24,"Journalist / P"=>11,"Activist / Neutral"=>15 } arr = [] hash1.each do |k,v| arr << {:data => k,:frequency => v} end arr.to_json 给 "[{"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}]" 你说你想要一个“javascript hash”,但是你的问题看起来像是一个没有方括号的数组.我的结果是一个有效的json对象表示,它是一个对象数组.我认为其实就是你想要的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |