javascript 从 json 子数组中获取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12373357/
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-10-26 16:02:17  来源:igfitidea点击:

Getting Data from a json sub array

javascriptjqueryjson

提问by Pit Digger

I am looping through the following json. I get id and name fine, but when I do json.templates[i].dailyemails.lengthit always returns 0.

我正在遍历以下 json。我得到 id 和 name 很好,但是当我这样做时json.templates[i].dailyemails.length它总是返回 0。

Here is my json:

这是我的 json:

{
   "templates":[
      {
         "id":"2c1d99d9b6b2fb417601d24c10c9b041a7d6f37b",
         "dailyemails":[
            "[email protected]",
            "[email protected]"
         ],
         "name":"Registration Report"             
      },
      {
         "id":"7d7cc642ca13cc4a998cad364dfe8e623fd95ae3",
         "dailyemails":[
            "[email protected]"
         ],
         "name":"Live Report"
      }

   ]
}

采纳答案by Darin Dimitrov

This should work just fine as seen in this live demo. Make sure that your actual JSON structure is the same as the one you have shown in your question.

这应该可以正常工作,如本现场演示所示。确保您的实际 JSON 结构与您在问题中显示的结构相同。

回答by Denys Séguret

If this is JSON, that is a string, you have to parse it and work with a javascript object :

如果这是 JSON,那是一个字符串,您必须解析它并使用 javascript 对象:

var obj = JSON.parse(json);

And then you may query obj.templates[i].dailyemails

然后你可以查询 obj.templates[i].dailyemails

回答by Shyju

$.each(data.templates,function(index,item){
    alert(item.dailyemails.length)
});

Sample : http://jsfiddle.net/JbF29/2/

示例:http: //jsfiddle.net/JbF29/2/