简体   繁体   English

如何解码 JSON object 并对其进行迭代?

[英]How to decode JSON object and iterate over it?

In this post I learned how to encode an object on the server side, and now I would like to decode it on the client side.这篇文章中,我学习了如何在服务器端对 object 进行编码,现在我想在客户端对其进行解码。

On the client side I do在客户端我做

$.ajax({
    type: "GET",
    url: "/cgi-bin/ajax_sort.pl",
    contentType: "application/json; charset=utf-8",
    dataType: "json",

    data: { "column" : this.id },

    error: function(XMLHttpRequest, textStatus, errorThrown) {
        showError('responseText: ' + XMLHttpRequest.responseText);
        showError('textStatus: ' + textStatus);
        showError('errorThrown: ' + errorThrown);
    },

    success: function(result){
        if (result.error) {
            showError(result.error);
        } else {

        var obj = jQuery.parseJSON(result);

        }
    }
});

Question问题

Does obj now contain the decoded JSON data? obj现在是否包含解码的 JSON 数据?

If so, the object looks like this one the server side (output from Perl's Data::Dumper )如果是这样,object 在服务器端看起来像这样(Perl 的Data::Dumper输出)

$VAR1 = {
          '127' => {
                     'owners' => [
                                   'm'
                                 ],
                     'users' => [
                                  'hh',
                                  'do'
                                ],
                     'date_end' => '24/05-2011',
                     'title' => 'dfg',
                     'date_begin' => '24/05-2011',
                     'members_groups' => [],
                     'type' => 'individuel'
                   },
          '276' => {
                     ...

Question问题

Is obj indeed contains the decoded JSON, how do I iterate over the object? obj是否确实包含解码的 JSON,我该如何迭代 object?

Because you specified the dataType: 'json' , result should already contain the Javascript object unserialized from the HTTP response.因为您指定了dataType: 'json'result应该已经包含从 HTTP 响应中反序列化的 Javascript object 。 $.parseJSON should be unnecessary. $.parseJSON应该是不必要的。

You can loop through it with $.each :您可以使用$.each循环遍历它:

success: function(result){
    if (result.error) {
        showError(result.error);
    } else {
        $.each(result, function(key, value) {
            alert(value.title).
        });
    }
}

result is already a JSON object - parsed by jQuery since you've specified dataType: "json" - so you shouldn't be parsing it. result已经是 JSON object - 由 jQuery 解析,因为您指定了dataType: "json" - 所以您不应该解析它。

To go over the data, you could do this:对 go 的数据,你可以这样做:

for(key in result){
    var curr = result[key];

    //iterate over owners    
     for(var i = 0; i < curr.owners.length; i++){
         alert(curr.owners[i]);
     }

    //iterate over users    
     for(var i = 0; i < curr.users.length; i++){
         alert(curr.users[i]);
     }

     alert(curr.data_end);
     alert(curr.title);

    //and so on...
}

Update更新

I keep forgetting about $.each() as shown in lonsomeday's answer - you might want to go with that instead.如 lonsomeday 的回答所示,我一直忘记$.each() - 你可能想用它来代替 go 。

You have to declare the data type of your AJAX request as JSON.您必须将 AJAX 请求的数据类型声明为 JSON。 jQuery will automatically "decode" this and create an object out of it. jQuery 将自动“解码”并从中创建一个 object。

You can immediately access the data via alert( result[127] );您可以通过alert( result[127] );

You can iterate over obj's members using for...in .您可以使用for...in遍历 obj 的成员。

for(var key in obj) {
    var value = obj[key];
    alert(key + "=" + value);
}

Note: There should be little reason for you to want to iterate over the members of a JSON object.注意:您应该没有什么理由要遍历 JSON object 的成员。 JSON is intended as a serialization format where both sides (client and server) know its structure. JSON 旨在作为双方(客户端和服务器)都知道其结构的序列化格式。 If you can help what data is transmitted, obj should be an array on its outmost scope.如果你能帮忙传输什么数据,obj应该是它最外面的一个数组scope。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM