我得到了这张红宝石地图
top_services = [["mfemve", "12,22"], ["vmtoolsd", "5,39"], ["zabbix_agentd", "1,89"]]
我需要将此映射转换为JSON对象并添加键像这样
{
{ "service_name" : "mfemve", "value" : "12,22" },
{ "service_name" : "vmtoolsd", "value" : "5,39" },
{ "service_name" : "zabbix_agentd", "value" : "1,89" }
}
我该怎么做?谢谢!
你需要json模块,然后使用zip映射你可以这样做:
require 'json'
top_services = [["mfemve", "12,22"], ["vmtoolsd", "5,39"], ["zabbix_agentd", "1,89"]]
keys = [:service_name, :value]
res = top_services.map { |e| keys.zip(e).to_h }.to_json
res
#=> "[{"service_name":"mfemve","value":"12,22"},{"service_name":"vmtoolsd","value":"5,39"},{"service_name":"zabbix_agentd","value":"1,89"}]"
考虑检查数字数据的小数分隔符,以防它是浮点数。