Quiero apuntar a un elemento específico en mi archivo JSON:
{ "taskMeta": "Some meta info", "tasksLib": [ { "task001": { "id":"1", "createDate":"01.02.17", "dueDate":"02.03.17", "author":"Author name", "tag":"Things", "description":"Here's a description of the todo", "priority":"1", "color":"danger", "title":"btn-danger", "content":"Here's the notes content" }, "task002": { "id":"2", "createDate":"02.02.17", "dueDate":"05.03.17", "author":"Author name", "tag":"Other things", "description":"Here's another description of the todo", "priority":"0", "color":"info", "title":"Foo", "content":"Here's some amazing content" } } ] }Luego se carga en este archivo js:
$.ajax({ type: 'GET', url: 'includes/tasks.json', dataType: 'json', success: function(task) { $.each(task, function(i, task){ console.log( task.taskLib[0].id ); ...Esto me da:
TypeError no capturado: no se puede leer la propiedad '0' de indefinido
Primero tienes que analizar tu JSON:
var tasksData = JSON.parse(task);Luego puede recorrer sus tareas de la siguiente manera:
$.each(tasksData.tasksLib, function(i, task){ console.log(task.id); }Algunas observaciones:
tasksLib , no taskLib Debe usar el método Object.keys() :
var keys=Object.keys(task.tasksLib[0]); console.log(task.tasksLib[0][keys[0]].id) var task={ "taskMeta": "Some meta info", "tasksLib": [ { "task001": { "id":"1", "createDate":"01.02.17", "dueDate":"02.03.17", "author":"Author name", "tag":"Things", "description":"Here's a description of the todo", "priority":"1", "color":"danger", "title":"btn-danger", "content":"Here's the notes content" }, "task002": { "id":"2", "createDate":"02.02.17", "dueDate":"05.03.17", "author":"Author name", "tag":"Other things", "description":"Here's another description of the todo", "priority":"0", "color":"info", "title":"Foo", "content":"Here's some amazing content" } } ] } var keys=Object.keys(task.tasksLib[0]); keys.forEach(function(item){ console.log(task.tasksLib[0][item].id) });