javascript - JSON.parse add property or func? -


is there way use json.parse function add properties or functions on newly created objects (whatever nesting level is) ?

using reviver option (https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/json/parse) understand can drop properties don't want or care when parsing json.

json.parse( '{"name":"toplevel",'+ ' "gibberish":"...",'+ ' "children":['+ '   {"name":"child1",'+ '    "gibberish":"..."'+ '   },'+ '   {"name":"child2",'+ '    "gibberish":"..."'+ '   }'+ ' ]'+ '}'  ,(key,value)=>{  if (key=="gibberish")  {   return undefined;  }  return value });  => {"name":"toplevel"  "children":[    {"name":"child1"},    {"name":"child2"}  ] } 

the code above remove gibberish property of objects created. add property (say uniqueid) ?

should traverse object tree again ? (and deal typeof (and bug) guess if property object rather null or array or ...)

you can create class has behavior want , assign json data instance.

function class() {...} class.prototype.accept = function(visitor) {...}; class.prototype.copyfromjson = function() {     delete this.gibberish;     this.children = this.children.map(function(child) {         child = object.assign(new childclass, child);         child.copyfromjson();         return child;     }); }; function childclass() {...} childclass.prototype.copyfromjson = function() {     delete this.gibberish;     ... } var instance = object.assign(new class, json.parse(json)); instance.copyfromjson(); 

Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -