在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
#虚拟网络拓扑的json数据 def topodata #@vnic = Vnic.all #flash.now[:notice] = 'Message sent!' #flash.now[:alert] = 'Message sent!' simple_json = { nodes: [{ name: 'bob', age: "22", awesome: "true" }, { name: 'bob', age: 22, awesome:true }], links: [{ name: 'bob', age: "22", awesome: "true" }, { name: 'bob', age: 22, awesome:true }] } vnet = Vnet.find(:all, :select => 'id,name,vswitch_id') vm = VirtualMachine.find(:all, :select => 'id,hostname,virtual_machine_container_id') vmc = VirtualMachineContainer.find(:all, :select => 'id,hostname') vswitch = Vswitch.find(:all, :select => 'id,uuid,virtual_machine_container_id,vnet_id,name') #vswitch 和 vmc有什么关系? vnic = Vnic.find(:all, :select => 'id,virtual_machine_id,vnet_id') #把所有的name放入nodes数组中 如:{"name":"vswitch1","type":"vswitch"} nodes = Array.new for i in 0..vswitch.size-1 do nodes.push({ name: vswitch[i].name.to_s, group: 1 #"vswitch" }) end for i in 0..vm.size-1 do nodes.push({ name: vm[i].hostname.to_s, group: 2 #"vm" }) end for i in 0..vmc.size-1 do nodes.push({ name: vmc[i].hostname.to_s, group: 3 #"vmc" }) end #储存名字和其在nodes中的位置,为了方便edges找到其位置 如:id_hash["vm2"] = 4 id_hash = Hash.new for i in 0..nodes.size-1 do id_hash[nodes[i][:name]] = i end #edges储存边之间的关系 #先储存vswitch和vm的关系 => vnic links = Array.new for i in 0..vnic.size-1 do links.push({ source: id_hash[vm[vnic[i].virtual_machine_id-1].hostname], target: id_hash[vswitch[vnet[vnic[i].vnet_id-1].vswitch_id-1].name], value: 10, des: "vswitch_to_vm" }) end #再储存vm和vmc的关系 => vm for i in 0..vm.size-1 do links.push({ source: id_hash[vm[i].hostname], target: id_hash[vmc[vm[i].virtual_machine_container_id-1].hostname], value: 5, des: "vm_to_vmc" }) end @alljson = {} @alljson["nodes"] = nodes @alljson["links"] = links #flash.now[:alert] = id_hash[vm[2].hostname] lsjson = { nodes: [ {name:"Myriel",group:1}, {name:"Napoleon",group:1}, {name:"Mlle.Baptistine",group:2}, ], links: [ {source:0,target:1,value:1}, {source:1,target:2,value:8}, {source:2,target:1,value:10}, ] } respond_to do |format| format.html format.json { render json: @alljson } #这里会自动调用to_json end #render json: lsjson #render json: {test: 1} end
ruby关于json格式的调用 首先json格式注意: 1、在nodes后面要紧跟:,不能有空格 2、nodes、name这些地方不能用引号括起来,不然不能用ruby转换为json格式 simple_json = { nodes: [{ name: 'bob', age: "22", awesome: "true" }, { name: 'bob', age: 22, awesome:true }], links: [{ name: 'bob', age: "22", awesome: "true" }, { name: 'bob', age: 22, awesome:true }] } render json: simple_json respond_to do |format| format.html format.json { render json: @alljson } #这里会自动调用to_json end |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论