標籤:des style blog http os io ar strong for
#虛擬網路拓撲的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 = SLB/VPC Operations and Maintenance System.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.newfor i in 0..vswitch.size-1 do nodes.push({name: vswitch[i].name.to_s,group: 1 #"vswitch" })endfor i in 0..vm.size-1 do nodes.push({name: vm[i].hostname.to_s,group: 2 #"vm" })endfor i in 0..vmc.size-1 do nodes.push({name: vmc[i].hostname.to_s,group: 3 #"vmc" })end#儲存名字和其在nodes中的位置,為了方便edges找到其位置 如:id_hash["vm2"] = 4id_hash = Hash.newfor i in 0..nodes.size-1 do id_hash[nodes[i][:name]] = i end#edges儲存邊之間的關係#先儲存vswitch和vm的關係 => vniclinks = Array.newfor 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的關係 => vmfor 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 }]}
3、(1)可以直接在controller的方法中直接render,就可以得到json格式的資料,比如
render json: simple_json
(2)或者另一種方法也可以,這裡的@alljson就是類似上面simple_json格式的資料,當然,如果直接是model裡匯出來的資料也可以直接用,比如@vnic = Vnic.all
respond_to do |format| format.html format.json { render json: @alljson } #這裡會自動調用to_json end
4、直接存取url http://localhost:3000/vnet/topodata.json就可以直接得到json資料了
在rubychina上看到如果在url上想不要後面.json就可以看到json資料的話,就要到route裡改resource直接為json資料了, routes裡面對特定的resource加上 format: :json 好像是這樣。
json格式在ruby和rails中的注意事項