【问题标题】:Accessing nested properties json访问嵌套属性 json
【发布时间】:2014-11-29 03:57:19
【问题描述】:

我有这个 json:

{"objects":[{"text":{"x":643,"y":71,"width":82,"height":33,"font":"Arial","style":"bold","size":24,"label":"Part A"}},
{"text":{"x":643,"y":116,"width":389,"height":42,"font":"Arial","style":"bold","size":16,"label":"What does \"novel\" mean as it is used in paragraph 8 of \"Turning Down a New Road\"? "}},
{"radiobutton":{"x":643,"y":170,"width":100,"height":20,"label":"A. old"}},{"radiobutton":{"x":643,"y":209,"width":100,"height":20,"label":"B. afraid"}},
{"radiobutton":{"x":643,"y":250,"width":100,"height":20,"label":"C. new"}},
{"radiobutton":{"x":643,"y":289,"width":100,"height":20,"label":"D. friendly"}}]}

我需要获取每个元素的属性,但是我无法获取第二级的属性,我的意思是我无法知道该元素是否为“文本”、“单选按钮”、“标签”,我三级属性没问题。

这是我的来源:

                   $.ajax({
                        url: 'generateobject.php',
                        dataType: 'json',
                        type: 'GET'
                    }).done(function(data) {
                        $.each(data, function(index, firstLevel) {
                            $.each(firstLevel, function(anotherindex, secondLevel) {
                                alert(secondLevel[0]);//shows [object Object]
                                $.each(secondLevel, function(yetAnotherIndex, thirdLevel) {
                                    //alert(thirdLevel.y+''+thirdLevel.y);
                                });
                            });
                        });
                    });

二级属性如何获取?

【问题讨论】:

标签: php jquery json nested


【解决方案1】:

使用Object.keys(data) 并访问第一项。如果您运行 sn-p,您应该会看到预期的类型警报:

var data = {"objects":[{"text":{"x":643,"y":71,"width":82,"height":33,"font":"Arial","style":"bold","size":24,"label":"Part A"}},
{"text":{"x":643,"y":116,"width":389,"height":42,"font":"Arial","style":"bold","size":16,"label":"What does \"novel\" mean as it is used in paragraph 8 of \"Turning Down a New Road\"? "}},
{"radiobutton":{"x":643,"y":170,"width":100,"height":20,"label":"A. old"}},{"radiobutton":{"x":643,"y":209,"width":100,"height":20,"label":"B. afraid"}},
{"radiobutton":{"x":643,"y":250,"width":100,"height":20,"label":"C. new"}},
{"radiobutton":{"x":643,"y":289,"width":100,"height":20,"label":"D. friendly"}}]};


$.each(data, function(index, firstLevel) {
  $.each(firstLevel, function(anotherindex, secondLevel) {
    alert(Object.keys(secondLevel)[0]);
    $.each(secondLevel, function(yetAnotherIndex, thirdLevel) {
      //alert(thirdLevel.y+''+thirdLevel.y);
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【讨论】:

    猜你喜欢
    • 2019-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-14
    • 2012-11-12
    • 2015-01-01
    • 1970-01-01
    • 2018-06-03
    相关资源
    最近更新 更多