我有一个带有下述格式的json文件
mydata.json
{
"nodes":{
"Aidan":{"color":"green", "shape":"dot", "alpha":1, "id" : "aidan"},
"Sofia":{"color":"green", "shape":"dot", "alpha":1},
"Liam":{"color":"GoldenRod", "shape":"dot", "alpha":1}
},
"edges":{
"Quinn":{
"Liam":{"length":2.5,"weight":2},
"Audrey":{"length":2.5,"weight":2},
"Noah":{"length":2.5,"weight":2},
"Claire":{"length":2.5,"weight":2}
},
"Liam":{
"Sofia":{"length":2.5,"weight":2},
"Ethan":{"length":2.5,"weight":2},
"Amelia":{"length":2.5,"weight":2}
}
}
}
我将使用jquery读取上面的文件数据,如下所述
var data = $.getJSON("data/mydata.json",function(data){
var nodes = data.nodes;
var edges = data.edges;
//i want to access first element or between element.
//like var edge = edges.get(0) or nodes.get("aidan")
})
我想访问第一个元素或元素之间的索引或对象的name属性。比如var edge = edges.get(0)或nodes.get(" aidan")。
谢谢
答案 0 :(得分:1)
有几种方法可以做到这一点
Object.keys(nodes)[0]; //retrieve the first key
edges['Quinn'];
edges.Quinn
第一个上面的一点警告,JS中的Object是无序的,因此它可能会中断,因此浏览器倾向于保持插入顺序。 希望它有所帮助
答案 1 :(得分:0)
试试此代码
nodes['aidan']
edges['Quinn']
答案 2 :(得分:0)
前面提到的代码
nodes['aidan']
或
nodes.aidan
应该同样合适。
答案 3 :(得分:0)
为您准备了fiddle
。你可以在那里查看。