在javascript中获取root json元素

时间:2012-08-06 10:28:36

标签: javascript json

这是我的json ...... 使用javascript ..我想在这种情况下只输出根的名称服务 然后遍历数组中的各个元素

{
    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: []
        }
    }
}

1 个答案:

答案 0 :(得分:3)

那不是JSON格式数据,你可以通过对象循环: 要获取根密钥,您可以执行以下操作:

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

并循环通过所有项目:

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