Easiest way to convert json data into objects with methods attached?

Posted by John Mee on Stack Overflow See other posts from Stack Overflow or by John Mee
Published on 2010-05-14T23:20:44Z Indexed on 2010/05/14 23:24 UTC
Read the original article Hit count: 217

Filed under:

What's the quickest and easiest way to convert my json, containing the data of the objects, into actual objects with methods attached?

By way of example, I get data for a fruitbowl with an array of fruit objects which in turn contain an array of seeds thus:

{"fruitbowl": [{
     "name": "apple", 
     "color": "red", 
     "seeds": []
   },{
     "name": "orange", 
     "color": "orange", 
     "seeds": [
        {"size":"small","density":"hard"},
        {"size":"small","density":"soft"}
    ]}
}

That's all nice and good but down on the client we do stuff with this fruit, like eat it and plant trees...

 var fruitbowl = []
 function Fruit(name, color, seeds){
     this.name = name
     this.color = color
     this.seeds = seeds
     this.eat = function(){
         // munch munch
     }
 }
 function Seed(size, density){
     this.size = size
     this.density = density
     this.plant = function(){
          // grow grow
     }
 }

My ajax's success routine currently is currently looping over the thing and constructing each object in turn and it doesn't handle the seeds yet, because before I go looping over seed constructors I'm thinking

Is there not a better way?

    success: function(data){           
        fruitbowl.length = 0
        $.each(data.fruitbowl, function(i, f){
            fruitbowl.push(new Fruit(f.name, f.color, f.seeds))
        })

I haven't explored looping over the objects as they are and attaching all the methods. Would that work?

© Stack Overflow or respective owner

Related posts about jQuery