Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 709
John Mee Avatar asked May 14 '10 23:05

John Mee


People also ask

Which method is used to convert JSON data to object?

JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON. parse() , as the Javascript standard specifies.

How do I convert a JSON file to an object?

Convert JSON String to JavaScript Object The JSON module offers two methods - stringify() , which turns a JavaScript object into a JSON String, and parse() , which parses a JSON string and returns a JavaScript object.

Can JSON objects have methods?

JSON is purely a string with a specified data format — it contains only properties, no methods. JSON requires double quotes to be used around strings and property names. Single quotes are not valid other than surrounding the entire JSON string.

Which method converts JSON data to a JavaScript object?

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.


2 Answers

Yes, it would work, but it's not desirable. Apart from appearing slightly hacky IMO, you're attaching methods to each instance of your fruit and seeds, where you should instead be using the prototype chain. If you're going to be using instanceof in the future, this method won't work anyway.

What you're currently doing is the best solution; and you'll be able to use instanceof.

If you're feeling adventurous, you can use JSONP instead of AJAX, with the JSONP response looking something like:

buildFruitbowl([new Fruit("orange", "blue", [new Seed("small", "hard"), new Seed("big", "soft")]), new Fruit("banana", "yellow", [new Seed("small", "hard"), new Seed("big", "soft")])]);

Which will save you having to do all your object looping, and you'll get your Fruit and Seeds how you want (and instanceof support); however I would still stick to what you're doing already.

Best of look growing your bananas.

like image 109
Matt Avatar answered Sep 20 '22 07:09

Matt


Pass the data to the object constructor then use jquery's "extend" to combine the data and methods:

 function Fruit(data){
     $.extend(this, data)
     this.eat = function(){
         // munch munch
     }
 }
 ...
       $.each(data.fruitbowl, function(i, f){
           fruitbowl.push(new Fruit(f))
       })

You still have loops involved; and must manually code loops for the nested objects (like seeds), but still a very simple way to get past the problem.

like image 25
John Mee Avatar answered Sep 21 '22 07:09

John Mee