在javascript中解析json字典以遍历键

alm*_*hty 7 jquery json

我有以下json数据来自web服务,这只是一个序列化为json的字典,现在在客户端我需要解析这个以使用javascript或jquery迭代这个json字典的键

{
   "AboutToExpire": {
      "Display": true,
      "Message": "Several of your subscriptions are about to expire. <a id=\"lnkShowExpiringSubs\" href=\"#\">View subscriptions<\/a>"
   },
   "Expired": {
      "Display": true,
      "Message": "Your McAfee WaveSecure - Tablet Edition subscription has expired and you’ve been without protection for 384 days. <a id=\"lnkNotificationRenewNow\" href=\"http://home.mcafee.com/root/campaign.aspx?cid=96035&pk=FAB37CF4-3680-4A87-A253-77E7D48BF6D7&affid=0\">Renew now<\/a>"
   }
}
Run Code Online (Sandbox Code Playgroud)

Shi*_*dim 23

使用JSON2.js

var obj = JSON.parse(data);
for(var key in obj){
    if (obj.hasOwnProperty(key)){
        var value=obj[key];
        // work with key and value
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 很好的解决方案。但是您不需要包含 JSON2.js,除非您正在查看非常旧的浏览器。当前所有浏览器都原生支持 parse() 和 stringify() 。 (2认同)

cra*_*man 5

var s = '{"AboutToExpire":{"Display":true,"Message":"Several of your subscriptions are about to expire. \u003ca id=\"lnkShowExpiringSubs\" href=\"#\"\u003eView subscriptions\u003c/a\u003e"},"Expired":{"Display":true,"Message":"Your McAfee WaveSecure - Tablet Edition subscription has expired and you’ve been without protection for 384 days. \u003ca id=\"lnkNotificationRenewNow\" href=\"http://home.mcafee.com/root/campaign.aspx?cid=96035&pk=FAB37CF4-3680-4A87-A253-77E7D48BF6D7&affid=0\"\u003eRenew now\u003c/a\u003e"}}';

var data = eval(s); // this will convert your json string to a javascript object

for (var key in data) {
    if (data.hasOwnProperty(key)) { // this will check if key is owned by data object and not by any of it's ancestors
        alert(key+': '+data[key]); // this will show each key with it's value
    }
}
Run Code Online (Sandbox Code Playgroud)

  • “ eval”被广泛的受众视为不安全。@ shiplu.mokadd.im的答案是更安全的选择。 (2认同)
  • 评估不足,请注意,这对外部数据不是一个好主意。 (2认同)