javascript - JSON.parse() breaks object function -


i have objects 'stringify'd json.stringify(), saved localstorage.setitem(), retrieved localstorage.getitem(), parsed json.parse(), , returned array of objects used within program. code:

var exampleobjects = [];  function objectexample() {     this.examplefunction = function() {             return this.otherobjectcreatedelsewhere.value;     }     this.otherobjectcreatedelsewhere; }  function main() {     exampleobjects[ 0 ] = new objectexample();     exampleobjects[ 0 ].otherobjectcreatedelsewhere = otherobjectcreatedelsewhere;     exampleobjects[ 0 ].examplefunction(); //works     var save0 = json.stringify( exampleobjects[ 0 ] );     localstorage.setitem( 'key', save0 );     save0 = localstorage.getitem( 'key' );     exampleobjects[ 0 ] = json.parse( save0 );     exampleobjects[ 0 ].examplefunction(); //no longer works, instead throws error exampleobjects[ 0 ].examplefunction not function }  main(); 

now i've looked json.parse reviver methods, cannot life of me figure out. have not gone school of this, hobby of mine, 1 i've been cultivating couple years now. enjoy it, times these frustrating.

edit

i have resolved invaluable advice cloudfeet. took objects saved json string parsed them objects, created new object , reassigned rich properties.

thanks again!

json not javascript. uses limited subset of javascript syntax, data types can encode are:

  • null
  • boolean
  • number
  • string
  • object: map string of types
  • array: list of values

(see http://json.org/)

json not capable of serialising functions. functions omitted (like undefined), prototypes destroyed, etc.

so: need convert rich objects (with methods etc.) json, , able convert again.


edit: rough example:

function myobj(name, age) {     this.name = name;     this.age = age;     this.hello = function () {         alert('hello, ' + this.name + '!');     }; } 

when serialise this, {"name": "sarah", "age": 38} - there no "hello" entry.

so, decode, need unpack it:

var array = json.parse(savedstring); // plain json (var = 0; < array.length; i++) {     var plainobj = array[i];     var richobj = new myobj(plainobj.name, plainobj.age); // reconstruct     array[i] = richobj; } 

this simple way, decode logic hard-coded - there ways make fancier, second parameters of json.stringify() , json.parse(), , .tojson() method, it's same thing, organised differently.


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -