Viktor Rudi
Viktor Rudi

Reputation: 75

How to access JSON element from jQuery Ajax

I want to target a specific element in my JSON file:

{
  "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"
         }

     }
  ]
}

Then it gets loaded in this js file:

$.ajax({
     type:     'GET',
     url:      'includes/tasks.json',
     dataType: 'json',
     success: function(task) {

        $.each(task, function(i, task){
           console.log(
              task.taskLib[0].id
           );
...

This gives me:

Uncaught TypeError: Cannot read property '0' of undefined

Upvotes: 1

Views: 1933

Answers (2)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48437

Some observations :

  1. It's tasksLib, not taskLib
  2. You should use Object.keys() method:

    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)
});

Upvotes: 0

Christos
Christos

Reputation: 53958

You have first to parse your JSON:

var tasksData = JSON.parse(task);

Then you can loop through your tasks as below:

$.each(tasksData.tasksLib, function(i, task){
    console.log(task.id);
}

Upvotes: 4

Related Questions