0

I have objects which are 'stringify'd with JSON.stringify(), then saved with localstorage.setItem(), then are retrieved with localstorage.getItem(), then are parsed with JSON.parse(), and finally are returned into an array of objects used within the program. This is my 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 is not a function
}

main();

Now I've looked up JSON.parse with reviver methods, but I just cannot for the life of me figure it out. I have not gone to school for any of this, this is just a hobby of mine, but one that I've been cultivating for a couple years now. I really enjoy it, but times like these are frustrating.

EDIT

I have resolved this with the invaluable advice from cloudfeet. Basically I took the objects from the saved JSON string then parsed them into objects, then created a new object and reassigned all the rich properties.

Thanks again!

1
  • 2
    Functions are not valid in JSON syntax. See json.org — you can have strings, numbers, objects, arrays, true, false, and null, but you can't have a function. Commented May 29, 2015 at 16:05

1 Answer 1

3

JSON is not JavaScript. It uses a limited subset of the JavaScript syntax, but the only data types it can encode are:

  • null
  • boolean
  • number
  • string
  • object: map from string to any of the types
  • array: list of values

(see http://json.org/)

JSON is not capable of serialising functions. Any functions will be omitted (like undefined), prototypes will be destroyed, etc.

So: what you need to do is convert from your rich objects (with methods etc.) into JSON, and then be able to convert back again.


EDIT: A rough example:

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

When you serialise this, you will get {"name": "Sarah", "age": 38} - there is no "hello" entry.

So, to decode, you need to unpack it:

var array = JSON.parse(savedString); // Plain JSON
for (var i = 0; i < array.length; i++) {
    var plainObj = array[i];
    var richObj = new MyObj(plainObj.name, plainObj.age); // reconstruct
    array[i] = richObj;
}

This is a simple way, with the decode logic hard-coded - there are ways to make it fancier, like the second parameters of JSON.stringify() and JSON.parse(), and the .toJSON() method, but it's roughly the same thing, organised differently.

Sign up to request clarification or add additional context in comments.

6 Comments

Ah okay, that makes so much sense! But is that what a reviver does? Would I try and design something that finds valueless properties, and then re-add methods/functions that way? E.g. if if this.prop = undefined then this.prop = function(){ stuff }? Do you think something like that would work?
You're better off reconstructing the object using the new MyObj() syntax than trying to add individual methods. And the reviver is a translation function - so, something that looks at the plain object, decides what type the value "should" be and returns a "real" version. It's more or less exactly the same code as I wrote in my example, but wrapped up differently. I've personally never used reviver functions.
This is great- I have to say. Thank you very much for taking the time to lay out this example for me. I will try this out. The reviver function idea, from what I was reading, is just a little too unfamiliar to me, but the way you explained everything was perfect and I will try and implement this now.
Unfortunately cloudfeet, I have not been able to get past the JSON.decode() part of this. I cannot find JSON.decode() from a few searches. Is this the only way to get a JSON string into an array? Thanks.
You're a hero- sorry about that last question. I have resolved this by doing what you've stated. Basically I took the objects from the saved JSON then parsed them, then created a new object and reassigned all the rich properties. Thanks again!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.