Can JSON serialize an array that uses * functions * as keys?
I am doing a Javascript linguistic project. I would like to build it with objects to represent nouns and functions to store verbs, as this makes conceptualizing my project less complicated. I am using functions as keys to an object (I wrote an example below). Will it be possible to serialize this with JSON when the time comes 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 thinking about my original question and reading the comments, I came to the conclusion that trying to do this is just very wrong and stupid.
a source to share
No, JSON cannot do this. Keys must be double quoted strings.
It also looks like you are not actually using this function as a key - it is 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>
a source to share
you are not actually using functions as keys - you are using the function's string transformation as a key, which also implicitly relies on these string representations to be unique. For platforms that support decompilation functions this works fine, but in theory there could be implementations that simply return "[function]", which would be very bad in your case.
a source to share
No, keys should always be strings and nothing else. See standard description .
And nouns
it is not an array, its a map, a hash table, an associative array, an "object", one of those, whatever the name you prefer.
a source to share