Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parsing json dictionary in javascript to iterate through keys

Tags:

json

jquery

I have the below json data coming from web service which is nothing but a dictionary serialized into json, now on client side i need to parse this back to iterate through the keys of this json dictionary using javascript or jquery

{
   "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>"
   }
}
like image 696
almighty Avatar asked Feb 04 '12 06:02

almighty


2 Answers

Use 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
    }
}
like image 59
Shiplu Mokaddim Avatar answered Oct 15 '22 06:10

Shiplu Mokaddim


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
    }
}
like image 32
craftsman Avatar answered Oct 15 '22 04:10

craftsman