Subj : Re: Serializing JavaScript in spidermonkey To : netscape.public.mozilla.jseng From : Brendan Eich Date : Tue Dec 30 2003 11:22 pm Marcello Bastea-Forte wrote: > Hey, > > I'd like to serialize a javascript object to a file, and I was wondering > if anyone has done this, and if there was any 'best' way to do it. In my experience there is no best way, because what hides behind a JS object can't be expressed in a literal form in the JS language, in full. > I don't need support for serializing objects (like functions and stuff) > other than some type of recursive property scanning and rebuilding. > Basically I want to store a recursive hashtable of the data (for a game > save state file). Do you have a general object graph, or a DAG, or even a tree? > I was thinking of using JS_Enumerate, and then writing that out to a > file (or maybe even generating javascript code, so reading in is > easier), then for all the basic types, doing JS_ValueToString, and for > objects, just a recursive call. Why do that when it's already been done, in the engine? See uneval and Object.prototype.toSource (and other .toSource prototype methods for the native classes). eval(uneval(o)) returns an object isomorphic to o, provided the graph rooted at o contains no native functions or other such objects that have no literal form. The uneval global function also works on primitive types, so uneval(true) returns "true", etc. /be .