简体   繁体   中英

get root json element in javascript

This is my json ... using javascript .. i want to output just the name of the root in this case services then traverse through the individual elements in the array

{
    services: {
        46: {
            servicetypeid: "27",
            serviceid: "51",
            servicename: "Parking",
            description: "Parking Related Payments",
            optioncode: [],
            inputid: [],
            price: [],
            categoryidentifier: []
        },
        47: {
            servicetypeid: "27",
            serviceid: "52",
            servicename: "Markets",
            description: "Markets Related Payments",
            optioncode: [],
            inputid: [],
            price: [],
            categoryidentifier: []
        },
        48: {
            servicetypeid: "27",
            serviceid: "53",
            servicename: "PSV",
            description: "Public Service Vehicles",
            optioncode: [],
            inputid: [],
            price: [],
            categoryidentifier: []
        }
    }
}

That's not JSON format data, you can loop thru the object: To get the root key, you could do:

var rootKey;
for(var prop in tst) {
 console.log( prop ); //will give "services"
 rootKey = prop;
}

And to loop thru all the items:

for( var key in tst[rootKey] ) {
  for( var key1 in tst[rootKey][key] ) {
    console.log( "key:" + key1 + " --- Value:"+ tst[rootKey][key][key1] );
 }
}

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