简体   繁体   中英

JSON objects and Javascript Objects

I am creating front-end of a web app. I am receiving all the responses in JSON, parsing it and putting it as html. I had a look at few javascript MVC frameworks (ie backbone.js, ember.js etc) and found that they were just overkill for my simple app. But what I found really fascinating is that they all had Models. I figured out I can create javascript objects and they will be similar to models and as I dont have such complex needs my custom javascript objects shall be easy to make.

function displayCar() {
  var result = "A Beautiful " + this.year + " " + this.make
    + " " + this.model;
  pretty_print(result);
}

function Car(make, model, year, owner) {
  this.make = make;
  this.model = model;
  this.year = year;
  this.owner = owner;
  this.displayCar = displayCar;
}

I receive the cars as JSON response from the server. SO what would be the ideal way : To create the objects while looping over the JSON array OR should I just use the parsing and directly show html from there?

Now my question is should I parse the JSON into javascript objects? I am also not sure if using this kind of objects would be much helpful? I would also like to know if there is a way to create custom pre-defined objects straight from JSON, as I feel than it might be useful like I want to car objects

Most modern javascript frameworks (jquery, angular, knockout, etc.) will parse the string representation to objects for you, it's not a step you need to worry about.

You don't need to pre-define anything, javascript is a loosely typed language - class definitions are not required. Essentially a JSON object is a big dictionary of property names to values, your web framework is responsible for serializing the server-side object into a JSON-compatible representation.

With regards to when you need to display the return data, I think that depends on the application you are building. If you need access to the cars indefinitely, then it may make sense to iterate over them and add methods as required, if however, you just want to display the data, do it when you receive it.

All this is to say, just return your objects from the server, and access the object and properties directly.

This is a method in the controller class, that responds to a URL (pseudo code)

public class Car { 
 string make;
 string model;
 string year;
 string owner;
}   

[Get("http://server/cars")]
public Car[] getCars()
{
  // the repository returns an array of Car objects, which in turn are returned to the client
  return myCarRepository.List(0, 25); // always page lists
}

Then on the client

jQuery
 .get("/server/cars")
 .success(function(carArray) {
    // carArray is an array of car objects that has been deserialized by jquery
    // you can access the properties using dot syntax
   console.log("server returned " + carArray.length + " cars");
   for (var i = 0; i < carArray.length; i++) {
     console.log("car[" + i + "].make = " + carArray[i].make);
     carArray[i].print = displayCar; // if you want to hold on to the array, and display info later, each object in the array has a print() method
   }
  });

I make some assumtions to answer your questions. Please tell me if any is wrong and i will edit the question accordingliy.

Question

I receive the cars as JSON response from the server. SO what would be the ideal way : To create the objects while looping over the JSON array OR should I just use the parsing and directly show html from there?

Answer

If you want to add some methods to each object on the array, you need those predefined "class".

Question

should I parse the JSON into javascript objects?

Answer

You will have to parse the JSON into a javascript Object just to use the data.

Question

Using this kind of objects would be much helpful?

Answer

If you are refering to Javascript objects, they are really useful and flexible. You can directly use the properties defined on the JSON from the Javascript object after it's parsed.

Suposse an array of Objects taken from JSON, as follows:

JSON_ARRAY = [
  {
    "make": "ACME inc",
    "model": "road runner 9999",
    "year": "the future",
    "owner": "nobody"
  },
  // more cars here...
]

you could access each car through JSON_ARRAY[n] , where n is the index of the car in the array.

you could also add your displayCar method to each object on the JSON_ARRAY

for (var i = 0; i < JSON_ARRAY.length; i++) {
    JSON_ARRAY.displayCar = displayCar;
}

Question

I would also like to know if there is a way to create custom pre-defined objects straight from JSON, as I feel than it might be useful like I want to car objects.

Answer

No, there isn't a way to pre-define a "class" from JSON. You can define a class designed to adapt to a JSON representation of itself, if you want.

function Car( car_json ) {
  this.make = car_json.make;
  this.model = car_json.model;
  this.year = car_json.year;
  this.owner = car_json.owner;
}

Car.prototype.displayCar = function() {
   // stuff
}

or even better:

function Car( json_data ) {
  for( var property in json_data ) {
      this[ property ] = json_data[ property ];
  }
}

Anyway, you will have to map the array of objects to an array of Cars:

var cars = JSON_CARS_ARRAY.map(function jsonToCar( json ) {
  return new Car( json );
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM