我有一个包含对象和数组的嵌套数据结构。我如何提取信息,即访问一个特定的或多个值(或键)?

例如:

var data = {
    code: 42,
    items: [{
        id: 1,
        name: 'foo'
    }, {
        id: 2,
        name: 'bar'
    }]
};

我如何访问项目中的第二个项目的名称?


当前回答

python式、递归式和函数式方法来分解任意JSON树:

handlers = {
    list:  iterate,
    dict:  delve,
    str:   emit_li,
    float: emit_li,
}

def emit_li(stuff, strong=False):
    emission = '<li><strong>%s</strong></li>' if strong else '<li>%s</li>'
    print(emission % stuff)

def iterate(a_list):
    print('<ul>')
    map(unravel, a_list)
    print('</ul>')

def delve(a_dict):
    print('<ul>')
    for key, value in a_dict.items():
        emit_li(key, strong=True)
        unravel(value)
    print('</ul>')

def unravel(structure):
    h = handlers[type(structure)]
    return h(structure)

unravel(data)

其中data是python列表(从JSON文本字符串解析而来):

data = [
    {'data': {'customKey1': 'customValue1',
           'customKey2': {'customSubKey1': {'customSubSubKey1': 'keyvalue'}}},
  'geometry': {'location': {'lat': 37.3860517, 'lng': -122.0838511},
               'viewport': {'northeast': {'lat': 37.4508789,
                                          'lng': -122.0446721},
                            'southwest': {'lat': 37.3567599,
                                          'lng': -122.1178619}}},
  'name': 'Mountain View',
  'scope': 'GOOGLE',
  'types': ['locality', 'political']}
]

其他回答

您可以通过这种方式访问它

data.items[1].name

or

data["items"][1]["name"]

两边相等。

解释很简单:

Var数据= { 42岁的代码: 项目:[{ id: 1、 名称:“foo” }, { id: 2 名称:“酒吧” }) }; /* 1. “data”对象包含“items”对象*/ console.log(数据); /* 2. ' items '对象包含两个对象作为元素的数组*/ console.log (data.items); /* 3.你需要数组的第二个元素-从'[0,1]' */中的' 1 ' console.log (data.items [1]); /* 4. 你需要第二个对象的' name '属性的值-数组的元素)*/ console.log (data.items [1] . name);

如果你愿意包含一个库,使用JSONPath将是最灵活的解决方案之一: https://github.com/s3u/JSONPath(节点和浏览器)

对于你的用例,json路径是:

$..items[1].name

so:

var secondName = jsonPath.eval(data, "$..items[1].name");

你需要做的非常简单,它可以通过递归来实现:

const json_object = {
        "item1":{
            "name": "apple",
            "value": 2,
        },
        "item2":{
            "name": "pear",
            "value": 4,
        },
        "item3":{
            "name": "mango",
            "value": 3,
            "prices": {
                "1": "9$",
                "2": "59$",
                "3": "1$"
            }
        }
    }
    
    function walkJson(json_object){
        for(obj in json_object){
            if(typeof json_object[obj] === 'string'){
                console.log(`${obj}=>${json_object[obj]}`);
            }else{
                console.log(`${obj}=>${json_object[obj]}`);
                walkJson(json_object[obj]);
            }
        }           
    }
    
    walkJson(json_object);
var ourStorage = {


"desk":    {
    "drawer": "stapler"
  },
"cabinet": {
    "top drawer": { 
      "folder1": "a file",
      "folder2": "secrets"
    },
    "bottom drawer": "soda"
  }
};
ourStorage.cabinet["top drawer"].folder2; // Outputs -> "secrets"

or

//parent.subParent.subsubParent["almost there"]["final property"]

基本上,在它下面展开的每个后代之间使用一个点,当你有由两个字符串组成的对象名称时,你必须使用["obj Name"]符号。否则,只要一个点就足够了;

来源:https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-objects

在此基础上,访问嵌套数组将如下所示:

var ourPets = [
  {
    animalType: "cat",
    names: [
      "Meowzer",
      "Fluffy",
      "Kit-Cat"
    ]
  },
  {
    animalType: "dog",
    names: [
      "Spot",
      "Bowser",
      "Frankie"
    ]
  }
];
ourPets[0].names[1]; // Outputs "Fluffy"
ourPets[1].names[0]; // Outputs "Spot"

来源:https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-arrays/

另一份描述上述情况的更有用的文件: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics#Bracket_notation

通过点走访问属性:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Dot_notation