Dade
Dade

Reputation: 241

working with JSON data, trying to parse nested data

I just working with JSON data and am playing around with jQuery and Ajax requests. Pretty basic stuff, but here's my problem.

I have a basic data set which I was using for time tracking. I know how to parse the simple JSON data like this:

{
        "end" : "1/18/2011",
        "start" : "1/18/2011",
        "task" : "Code Review",
},

It's the more complicated stuff I'm trying to parse like this where I'm trying to pull the "time" data out.

  {
        "end" : "1/17/2011",
        "start" : "1/17/2011",
        "task" : "Exclusive Brands",
        "time" : {
           "analysis" : 4,
           "documentation" : 3,
           "meetings" : 2
        }

This is the code for the script I've been using to parse the simple data:

$(function() {
    $('.load').click(function(){
        $.getJSON("data.js",function(data){
            $.each(data.timesheet, function(i,data){
            var div_data ="<div class='box'>"+data.start+" "+data.task+"</div>";
            $(div_data).appendTo("#time-tracking");
                });
            }
        );
        return false;
    });
});

My question is what's the format to parse the time data, or what's the best way to parse the information nested inside the time element?

Any help will be greatly appreciated.

Upvotes: 2

Views: 1241

Answers (2)

steveyang
steveyang

Reputation: 9288

A JSON string will be parsed into an object. When parsed, the time is the key of one object. You could retrieve the value of this object through the dot operator (.).

data = JSON.parse('{"end":"1/17/2011", "start":"1/17/2011", "task":"Exclusive Brands", "time": {"analysis":4, "documentation":3, "meetings":2 } }')
// => obj
data.time.analysis
// => 4

In your case similarly you could use the data.time.meetings to access your data from remote server.

Upvotes: 4

Bojin Li
Bojin Li

Reputation: 5789

Unless I am terribly mistaken, since jquery already converted data into a javascript for you, you should be able to access time as if it was a javascript object like so:

var analysis = data.time.analysis;
var documentation =  data.time.documentation;
var meetings = data.time.meetings;

etc...

Upvotes: 0

Related Questions