13

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>"
   }
}
2
  • will you please make it(json data) readable first?? Commented Feb 4, 2012 at 7:13
  • 1
    What have you tried? Also, what is your question? Commented Feb 4, 2012 at 10:25

4 Answers 4

30

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
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Good solution. But you don't need to include JSON2.js unless you're looking at very old browsers. All current browsers have parse() and stringify() supported natively.
Shouldn't you swap if (obj.hasOwnProperty(key)){ and for(var key in obj){ for performance reasons?
@Neolisk Nope. See carefully! The code says for each key in object and if this key is the obj's own property set value ...
@shiplu.mokadd.im: Yep, you are right, sorry. I am coming from the C# world, where such syntax is weird to say the least. +1 :)
9
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
    }
}

2 Comments

eval is deemed unsafe by a wide audience. @shiplu.mokadd.im's answer is the safer option.
Downvote for eval, please note that this is a bad idea on external data.
1

Parse it back to? You could just iterate over it as the object that it is.

Say you defined your JSON object as a variable through a closure or something, or for the sake of example just as a variable hardcoded... IE:

var myJSON = "{"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"}}"

with jquery's each() you can just iterate over it like.

$each(myJSON, function(x){document.print(myJSON.AboutToExpire[x].Message);`});

2 Comments

I need to check for the key and do some manipulation for example if the key is AboutToExpire or something else i need to apply some class and for other keys other class on the value which is Message in this case
Moreover myJSON.AboutToExpire is coming as undefined
0
  • the flask web server example below uses jsonify(dict)
  • javascript can iterated over the returned json dict without any additional conversions
  • this is a working example from 2020 (the original op/replies are from 2012)

'

-- DICTIONARY -- playlist dict
{'37wuvQZF06evO3kppDB': {'Display Name': 'Spotify',
                         'Duration': '0',
                         'Playlist Id': '37iloxevO3kppDB',
                         'Playlist Name': 'This Is Olan Mill',
                         'Public': 'Private',
                         'Tracks': '50',
                          'User Id': 'spotify'},
 '3VgKlrplm4BATKwHdDi': {'Display Name': 'Spotify',
                         'Duration': '0',
                         'Playlist Id': '3VgKlm4BATKwHdDi',
                         'Playlist Name': 'The Magic Of The Oboe',
                         'Public': 'Private',
                         'Tracks': '16',
                         'User Id': 'spotify'}}


-- Python Flask JSONIFY -- return the playlist dict
@app.route("/Playlists", methods=['get', 'post'])
def Playlist():
  cookieDump('Playlists')
  if request.method == 'POST':
    if request.form.get('getPlDict') == 'getPlDict':
      print('/Playlists getPlDict')
      return jsonify(session['mPlDict'])

  retVal = oLoader.loadPlDict()
  return render_template("plTable.html")


-- JAVASCRIPT -- load playlist into a html table
$.post(vUrl, { getPlDict: "getPlDict"}, function(plDict, status)
{
  $.each(plDict, function(key, val)
  {
      var rowNode = vPlTable.row.add(['', val['Playlist Name'], val['Tracks'], val['User Id'],
                                          val['Display Name'], val['Public'], val['Playlist Id']]);
  })
  vPlTable.draw();
});

'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.