简体   繁体   中英

Is their is anyway to make json object schema fixed i.e always contains same key

Is their is anyway to make json object schema fixed so that whenever i will create new object it will show same fixed number of key. So that i can change the value for that key whenever required(As like setter and getter).

You're probably mixing json and javascript.

JSON is a data format for communication, it can be used to serailiaze javscript object to the server, but the server can serialize his own objects into JSON, wheter they come from nodeJS, Java, or whatever.

So let's assume you're talking about javascript, this is really easy let's say you want an object People with the field name , *firstname**, dateOfBirth . You can just create a class with his constructor like this :

// creating based fields 
function People(){
    this.name = null;
    this.firstname = null;
    this.dateOfBirth = null;
}
// instantiating objects : 
var myPeople = new People();

But with that we can still do something like myPeople.foo = "bar". There is no way of preventing that in javascript. However you can make sure yourself that extrafield won't getserialized in JSON with something like this :

// adding method toJson to people
People.prototype.toJson = function(){
    return JSON.stringify({name:this.name, firstname:this.firstname, dataOfBirth:this.dateOfBirth});
};
// using it
var myJsonString = myPeople.toJson();

So any extra field you could have need for some manipulation will be ignore on serializing to the serving. I advsied you that because you not only to filter you keys, but to translate some objects before serializing. For instance i never serialize Javascript Date object, i always take the Timestamp (from getTime() method).

I don't know if i understand your question clearly but here is what i came up with:

var schema = function(){   
  var a=0;
  var b=2;

  var getA = function(){
    return a;
  }
  var setA = function(newValue){
    a = newValue;
  }
  return {
   getA:getA,
   setA:setA
  }

}

Then when you want a new instance you can do this.

var x = new schema();
x.setA(25);
x.getA();

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