简体   繁体   中英

How to access first or specific object from json data

I have a json file with below mentioned format

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}
        }
    }
}

I will be reading above file data using jquery as mentioned below

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")
})

I want to access first element or between element with the index or by name property of object. like var edge = edges.get(0) or nodes.get("aidan").

Thanks

There are several ways of doing it

Object.keys(nodes)[0]; //retrieve the first key
edges['Quinn'];
edges.Quinn

A little warning on the first one, Object in JS are unordered so it may break, thus browser tends to keep the insertion order. hope it helped

Try this code

nodes['aidan']
edges['Quinn']

Either the before mentioned code

nodes['aidan']

or

nodes.aidan

should work equally fine.

Prepared a fiddle for you. You can check there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM