Serialize a working JavaScript object as JSON retaining only properties? -


imagine have typed heirarchy in javascript this:

function person( newname ) {     this.name = name;     this.hats = [] } person.prototype = {     findhat : function( hatname ) {         var i=0;         ( i; i< this.hats.length; i++ )          {              if ( hats[i].name === hatname )               {                  return hats[i];              }          }          return { name: "no hat found" };     } }  function hat( name, description )  {     this.name= name;     this.description = description; } 

now able create instances...

var bob = new person( "bob" ); bob.hats.push( new hat("top hat", "very smart.")); bob.hats.push( new hat("wooly hat", "very warm.")); 

... , serialise them in way gets simple properties , records object hierarchy not functions, can deserialise them directly types, if - example - wanted change behaviour of findhat load stored data redefined person type safely. this:

"person:{"name":"bob","hats":[hat:{"name":"top hat","description":"very smart."}, hat:{"name":"wooly hat","description":"very warm."}]}"

obviously, highly simplified model, dealing complex , potentially deep object hierarchy in real life if can avoid having create further types or manually create serialisation , deserialisation methods on classes, ideal.

the project entirely written javascript running in browser , thinking either store data in local store or post server, assumption json natural way this, haven't worked pure json serialisation whole lot , looks though favours anonymous types, make hard me relate data object type. there simple way ( or standard library ) or need set explicitly serialising appears have been case few years ago?

both json.parse , json.stringify let plug they're doing, can customize serialization. also, can add tojson method type's prototype objects called serialize them json, letting control process.

json.stringify lets customize serialized result in 2 ways:

  1. if object has tojson method, json.stringify uses that.

  2. it lets specify "replacer" function called each item being serialized, in order give chance customize serialization bit. use opportunity mark output object type want have when comes in.

json.parse lets specify "reviver" function converse. special serialized type property on raw object, , use combined raw object data create typed object.

i went looking example of using these, and...er...um...happened find my own answer question going detail. :-)


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -