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

Best or Correct way for accessing json object?

我有 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<br>' + 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 = '<div class="clearfix panelPoll">';

                    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 += '<div class="row bg-info"><p>' + theQ + '</p><code>Total voter: <span class="badge">' + totalVoter + '</code></span></div>';
                        template += '<div class="clearfix"></div>';
                        template += '<div class="row resultPollBody">';
                        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 += '<p class="text-primary">' + data[0][1][j].choice + ' <span class="badge">' + data[0][1][j]['tbAns'] + '</span></p>';
                                template += '<div class="progress">';
                                template += '<div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="' + percent + '" aria-valuemin="0" aria-valuemax="100" style="width:' + percent + '%;">' + percent + '%</div>';
                                template += '</div>';
                            })(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 += '<div class="row bg-info"><p>' + theQ + '</p><code>Total voter: <span class="badge">' + totalVoter + '</code></span></div>';
                        template += '<div class="clearfix"></div>';
                        template += '<div class="row resultPollBody">';
                        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 += '<p class="text-primary">' + data[0][1][j].choice + ' <span class="badge">' + data[0][1][j]['tbAns'] + '</span></p>';
                                template += '<div class="progress">';
                                template += '<div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="' + percent + '" aria-valuemin="0" aria-valuemax="100" style="width:' + percent + '%;">' + percent + '%</div>';
                                template += '</div>';
                            })(j)
                        }
                    }

                    //closing tag for template
                    template += '</div></div>';

                    $('#' + parental).html(function() {
                        $(this).html(template);
                    });
                })
            }
        })
    });
});

因此,我声明变量以访问 JSON object,为了简单起见,我没有检查整个代码,而是在此处剪切了 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响应的第一层是数组的原因是因为响应中可能还有其他questions/objects。

如果是这样,那么您可能希望始终使用 $.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