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

时间:2012-02-04 06:40:46

标签: jquery json

我有来自web服务的以下json数据,这只是一个序列化为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>"
   }
}

4 个答案:

答案 0 :(得分: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
    }
}

答案 1 :(得分:4)

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 :(得分:1)

把它解析回来?您可以将其作为对象进行迭代。

假设您通过闭包或其他东西将JSON对象定义为变量,或者为了示例而将其定义为硬编码变量... 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"}}"

使用jquery的each(),你可以像迭代一样迭代它。

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

答案 3 :(得分:0)

  • 下面的 Flask Web 服务器示例使用 jsonify(dict)
  • javascript 可以遍历返回的 json dict,无需任何额外的转换
  • 这是 2020 年的工作示例(原始操作/回复来自 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();
});

'