jQuery jquery读取嵌套的json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4017122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:30:53  来源:igfitidea点击:

jquery reading nested json

jqueryjsonnested

提问by wmitchell

I have the following json as seen below. I'm trying to read the values TOP1, TOP2. I'm a little unsure of how to do this.

我有以下 json,如下所示。我正在尝试读取值 TOP1、TOP2。我有点不确定如何做到这一点。

I'm using the following .. But that just gets me an object which has the nested objects for TOP1 and TOP2. How do I get the values TOP1 and TOP2 ??

我正在使用以下.. 但这只是让我得到一个对象,其中包含 TOP1 和 TOP2 的嵌套对象。我如何获得 TOP1 和 TOP2 的值?

$.getJSON('http://localhost/data/menufixed.json',
    function(data) {            
        $.each(data, function(entryIndex, entry) {
            var html = '<li class="top-level">';

        });
    });

And the data below

还有下面的数据

{
"actions" : [
    {
        "action": "TOP1",
        "subaction": [
            {
                "name": "A" 
            },
            {
                "name": "B" 
            },
            {
                "name": "C" 
            } 
        ] 
    },
    {
        "action": "TOP2",
        "subaction": [
            {
                "name": "X" 
            },
            {
                "name": "Y" 
            } 
        ] 

回答by Nick Craver

It looks like you want to loop though the .actions, so change this:

看起来你想通过 循环.actions,所以改变这个:

$.each(data, function(entryIndex, entry) {
  var html = '<li class="top-level">';
});

To this:

对此:

$.each(data.actions, function(entryIndex, entry) {
  var html = '<li class="top-level">' + this.action + '</li>';
});

Using data.actionsyou're now looping through that array of objects, and thoseobjects are the ones with the .actionproperty, for example: "TOP1"and "TOP2".

使用data.actions您现在正在遍历该对象数组,这些对象是具有.action属性的对象,例如:"TOP1""TOP2"