Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse Json object in javascript

hello all i have one json object like

{"event1":{"title":"My birthday","start":"12\/27\/2011 10:20 ","end":"12\/27\/2011 00:00 "},"event2":{"title":"My birthday again","start":"12\/27\/2011 10:20 ","end":"12\/27\/2011 00:00 "}}

and i want to parse it like

[
            {
                title: 'All Day Event',
                start: new Date(y, m, 1)
            },
            {
                title: 'Long Event',
                start: new Date(y, m, d-5),
                end: new Date(y, m, d-2)
            }]

How will i do this. i wrote this code but its givin array length 0 my code is

var response = eval(data);
        $.each(response, function() {
            obj = {};
            $.each(this, function(k, v) {
                if(k=="start")
                {
                    obj[k] = new Date(v);
                }
                if(k=="end")
                {
                    obj[k] = new Date(v);
                }
                else
                {
                    obj[k] = v;
                }
                event_data.push(obj);

            });

        });
like image 476
Lalit Chattar Avatar asked Dec 26 '11 09:12

Lalit Chattar


2 Answers

data = JSON.parse('{"event1":{"title":"My birthday","start":"12\/27\/2011 10:20 ","end":"12\/27\/2011 00:00 "},"event2":{"title":"My birthday again","start":"12\/27\/2011 10:20 ","end":"12\/27\/2011 00:00 "}}')

arr = []
for(var event in data){
    var dataCopy = data[event]
    for(key in dataCopy){
        if(key == "start" || key == "end"){
            // needs more specific method to manipulate date to your needs
            dataCopy[key] = new Date(dataCopy[key])
        }
    }
    arr.push(dataCopy)
}

alert( JSON.stringify(arr) )
like image 165
Billy Moon Avatar answered Oct 01 '22 09:10

Billy Moon


It looks like you're already using jQuery so just use $.parseJSON. (http://api.jquery.com/jQuery.parseJSON/)

You'll have to iterate over the object that is created though to turn the date strings into Date objects.

like image 33
Corbin Avatar answered Oct 01 '22 07:10

Corbin