访问json对象的最佳或正确方法?

我有以下格式的json响应:

[ { "0": [ { "tVote": "32" } ], "1": [ { "choice": "Barcelona", "tbAns": "2" }, { "choice": "Bayern Muenchen", "tbAns": "2" }, { "choice": "Juventus", "tbAns": "20" }, { "choice": "Manchester United", "tbAns": "5" }, { "choice": "Real Madrid", "tbAns": "3" } ], "2": [ { "question": "Favorite football team ?" } ], "status": "positive", "msg": "Thank you, your vote has been count." } ] 

到目前为止,我在以下代码中使用jQuery ajax访问它:

 $(function() { $('.vote').click( function(e) { e.preventDefault(); var parId = $(this).closest('form').attr('id'); var itemId = $(this).prev('input[name=q_id]').val(); var formAction = $('#' + parId).attr('action'); $.ajax({ type : 'POST', url : formAction, data : $('#' + parId + '').serializeArray(), dataType : 'json', beforeSend: function() { $('.loadPoll-' + itemId).removeClass('hidden'); }, error : function(request, status, error) { $('#' + parId).html('sorry can\'t send your request, please try again later
' + status + ' ' + error); }, success : function(data) { $('.loadPoll-' + itemId).addClass('hidden'); $.each(data, function() { var theQ = data[0][2][0]['question']; var msg = data[0]['msg']; var status = data[0]['status']; var totalVoter = data[0][0][0]['tVote']; var item = data[0][1]; var itemLength = data[0][1].length; var itemChoice = data[0][1][0].choice; var parental = $('.vote:focus').closest('form').attr('id'); //create html template for response var template = '
'; if(status === 'negative') { $.amaran({ content : { bgcolor: '#FF9900', message: msg, color : '#fff', icon : 'fa fa-download' }, theme : 'colorful', position : 'bottom right', cssanimationIn : 'swing', cssanimationOut: 'bounceOut' }); template += '

' + theQ + '

Total voter: ' + totalVoter + '
'; template += '
'; template += '
'; for(var j = 0; j < itemLength; j++) { //console.log(data[0][1][j].choice); // (debug only)return loop of answer //console.log(data[0][1][j]['tbAns']) // (debug only)return loop of total voter per answer var percent = Math.round((data[0][1][j]['tbAns'] / totalVoter) * 100); (function(j) { template += '

' + data[0][1][j].choice + ' ' + data[0][1][j]['tbAns'] + '

'; template += '
'; template += '
' + percent + '%
'; template += '
'; })(j) } } else if(status === 'positive') { //code here for new vote $.amaran({ content : { bgcolor: '#008000', message: msg, color : '#fff', icon : 'fa fa-download' }, theme : 'colorful', position : 'bottom right', cssanimationIn : 'swing', cssanimationOut: 'bounceOut' }); template += '

' + theQ + '

Total voter: ' + totalVoter + '
'; template += '
'; template += '
'; for(var j = 0; j < itemLength; j++) { //console.log(data[0][1][j].choice); // (debug only)return loop of answer //console.log(data[0][1][j]['tbAns']) // (debug only)return loop of total voter per answer var percent = Math.round((data[0][1][j]['tbAns'] / totalVoter) * 100); (function(j) { template += '

' + data[0][1][j].choice + ' ' + data[0][1][j]['tbAns'] + '

'; template += '
'; template += '
' + percent + '%
'; template += '
'; })(j) } } //closing tag for template template += '
'; $('#' + parental).html(function() { $(this).html(template); }); }) } }) }); });

所以,我声明变量来访问JSON对象,为了简单而不是检查整个代码,我在这里删除了var行:

 var theQ = data[0][2][0]['question']; var msg = data[0]['msg']; var status = data[0]['status']; var totalVoter = data[0][0][0]['tVote']; var item = data[0][1]; var itemLength = data[0][1].length; var itemChoice = data[0][1][0].choice; var parental = $('.vote:focus').closest('form').attr('id'); 

它的工作没有错,我得到了我想要的结果,但我想知道我在标题中说明,这是访问JSON的正确方法还是有正确和简单的方法?

提前致谢。

JSON响应是您的代码的一部分吗?

因为我肯定会花一些时间改进那个javascript对象结构,如果这是在你的控制之下。

例如,为什么在"2"内的数组内有问题? "0""1"

为什么不只是:

 [ { "question": "Favorite football team ?", "tVote": "32", "choices": [ { "choice": "Barcelona", "tbAns": "2" }, ... ], "status": "positive", "msg": "Thank you, your vote has been count." }, { "question": "Another question ?", ... } ] 

如果您进行了这些更改,您访问此代码的javascript代码将更容易阅读。

正确使用$ .each

您总是使用data[0] ,但我认为JSON响应的第一级是一个数组的原因是因为响应中可能还有其他问题/对象。

如果这是真的,那么您可能希望始终使用$.each中的每个子对象而不是data[0]

 $.each(function(index, obj) { var theQ = obj[2][0]['question']; //notice "obj" instead of "data[0]" ... } 

使用变量而不是复制代码

在更深入的JSON结构中创建变量并使用中间步骤中的变量。 这将有助于您提高代码可读性。

例如:

 var item = obj[1]; // according to what I said about $.each var itemLength = item.length; // instead of obj[1].length var itemChoice = item[0].choice; // instead of obj[1][0].choice