如何从JSON中提取值键

时间:2016-02-15 15:17:59

标签: javascript arrays json key

我有以下JSON格式,我想从中提取密钥。

我想获得以下密钥

covg_AccdntDeath_Slf,
covg_DILong_Slf,
covg_LITwentyYr_Slf,
covg_LITenYr_Slf,
covg_GrpOffOvr_Slf,
covg_LIAnnual_Slf,
txtCampaignCode,
associationAccronym < /强>

这是我的JSON数据:

{  
  "covg_AccdntDeath_Slf":{  
    "txtGNumber":"G-29003-0",
    "txtPlanName":"Accidental Death and Dismemberment Insurance",
    "hidProdCode":"999",
    "rdTypeOfCovg":"New",
    "slidBenefitAmt":"50000",
    "productCategory":"AD"
  },
  "covg_DILong_Slf":{  
    "txtGNumber":"G-29002-0",
    "txtPlanName":"Long Term Disability",
    "hidProdCode":"601-a",
    "rdTypeOfCovg":"New",
    "txtMaxBenefitAmt":"$15,000",
    "selWaitingPeriod":"30 Days",
    "slidMonBenefitAmt":"1000",
    "productCategory":"DI"
  },
  "covg_LITwentyYr_Slf":{  
    "txtGNumber":"G-29005-0",
    "txtPlanName":"20-Year Level Term Life Insurance",
    "hidProdCode":"121",
    "rdTypeOfCovg":"New",
    "slidBenefitAmt":"100000",
    "productCategory":"LI"
  },
  "covg_LITenYr_Slf":{  
    "txtGNumber":"G-29004-0",
    "txtPlanName":"10-Year Level Term Life Insurance",
    "hidProdCode":"102",
    "rdTypeOfCovg":"New",
    "slidBenefitAmt":"100000",
    "productCategory":"LI"
  },
  "covg_GrpOffOvr_Slf":{  
    "txtGNumber":"G-29002-1",
    "txtPlanName":"Office Overhead Expense Disability Insurance",
    "hidProdCode":"603",
    "rdTypeOfCovg":"New",
    "slidBenefitAmt":"1000",
    "txtMaxBenefitAmt":"$20,000",
    "selWaitingPeriod":"30 Days",
    "selBenefitDuration":"24 months",
    "productCategory":"OO"
  },
  "covg_LIAnnual_Slf":{  
    "txtGNumber":"G-29000-0",
    "txtPlanName":"Traditional Term Life Insurance",
    "hidProdCode":"99999",
    "rdTypeOfCovg":"New",
    "slidBenefitAmt":"100000",
    "productCategory":"LI"
  },
  "txtCampaignCode":"",
  "associationAccronym":"ACS"
}

我尝试过以下代码。

 <html>
    <head>
        <script>
            var input = above JSON String.
        var keys = [];
        console.log('Length : '+input.length);
        for(var i = 0;i<input.length;i++)
        {
            Object.keys(input[i]).forEach(function(key){
                if(keys.indexOf(key) == -1)
                {
                    keys.push(key);
                }
            });
        }
        console.log('KKKK: '+keys);
        </script>
    </head>
</html>

1 个答案:

答案 0 :(得分:0)

您不需要所有代码。

1)将JSON解析为对象:var obj = JSON.parse(json);

2)对象没有长度,因此使循环冗余。 Object.keys(obj)确实有一个长度。

3)您正在迭代对象键并将它们放在一个新数组中。 Object.keys(obj)无论如何返回一个数组,因为在对象中键不能重复,检查当前键是否在keys中的条件也是多余的。

您需要的只是Object.keys(obj),然后您可以使用forEach来迭代数组。

类似的东西:

var keys = Object.keys(obj);
keys.forEach(function (el) { console.log(el); });

甚至只是:

Object.keys(obj).forEach(function (el) { console.log(el); });