gpt4 book ai didi

javascript - ruby 哈希到 javascript 哈希

转载 作者:数据小太阳 更新时间:2023-10-29 06:06:49 25 4
gpt4 key购买 nike

我有一个 ruby​​ 散列,我想将其转换为特定的 javascript 散列。
这是 ruby 哈希 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", frequency: (2) },

...

{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​​ 散列的第一个元素 frequency=24 并且不转义 Former Administration 中的空格>。为什么?

最佳答案

有一个 to_json 方法可以将 ruby​​ 哈希和数组转换为 json 对象。您可以使用第一个哈希创建一个哈希数组,然后对其调用 to_json。然后,您将在 ruby​​ 中进行所有数据操作,最后只需将格式转换为 json。

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

给予

"[{"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 散列”,但您的问题最后看起来像是一个没有方括号的数组。我的结果是一个有效的 json 对象表示,它是一个对象数组。我认为这实际上是您想要的。

关于javascript - ruby 哈希到 javascript 哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21605966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com