views:

261

answers:

5

I'm dabbling with a linguistics Javascript project. I'd like to build it using objects to represent Nouns and functions to store Verbs as this makes conceptualizing my project less difficult. I'm using functions as keys to an object (I've written an example below). Will it be possible to serialize this with JSON when it comes time to save the data.

function verbFn() {
   //do something
}

var nouns = {};

nouns[verbFn] = 'some value';

In this example, will JSON be able to serialize "nouns"?


Uh... after reflecting on my original question and reading the comments I've come to the conclusion that trying to do things this way is just very wrong and silly.

+4  A: 

No, JSON can't do this. The keys have to be double-quoted strings.

Also it looks like you're not actually using the function as a key - it's being converted to a string:

<script>

var x = {};
x[window.open] = true;

for (var i in x)
    alert(typeof i + '\n' + i); // typeof i == string

</script>
Greg
cool - i thought mistakenly that some sort of internal pointer to the function was being used, but nevertheless this could be workable. since the function name is saved as part of the string, i won't wind up with the same key twice. i just need to eval the functions that get saved to the db. the merit is that during design, using functions makes keeping track of nouns,verbs clearer.
username
...although you would never guess from the messy, lobotomized sample i used above ;-)
username
+1  A: 

According to the standards no you can't. The key has to be a string

Nadia Alramli
A: 

No, keys should always be strings and nothing else. See the standard description.

And nouns is not an array, it's map, hash table, associative array, "object", one of those, whatever name you prefer.

vava
it is an Object :-)
mdja
Yeah, forgot this one :)
vava
i'm using the term array loosely here but point taken.
username
A: 

JSON is a data structure syntax. A function is not data, so there is no way it can be serialised as part of a data structure (key or otherwise). Regardless of language, implementation or whatever else.

mdja
A: 

you are not really using functions as keys -- you are using the string conversion of a function as key, which also implicitly relies on those string representations being unique. For platforms that support decompiling functions this works fine, but theoretically there could be implementations that just return "[function]" which would be pretty bad in your case.

fforw