entrendipity/gremlin-node — pull request #17 by jcamins (2013-08-06 18:06:37+00:00)
Title: Add toJSON utility function to HashMap

When working with side effects, the lack of a convenient way to
convert the Java HashMap object into a node object is a serious
detriment. This patch adds two methods to the HashMap prototype:
map.toJSON() and map.toJSONSafe(). The methods allow one to do
the following:

var map = new g.HashMap();
g.V().groupBy(map, '{it}{it.out}').iterate();
console.log(map.toJSON());
# {
# 'v[40004]': [],
# 'v[4]': [
# 'v[40004]',
# 'v[40004]'
# ],
# 'v[80004]': []
# }

(note: JSON reformatted to make it clear that the desired structure
is in fact retained).

The difference between the two methods is VERY IMPORTANT. Because
JSON cannot handle null keys in objects, any null keys in the map
object must be deleted before serialization. The map.toJSON() method
does this in place, altering the original HashMap and destroying any
data that might have been in the JSON-illegal map[null].
map.toJSONSafe() makes a copy of your HashMap before remove the null
key. This makes it much safer, but depending on the complexity of your
HashMap could have side effects, since the clone will copy the entire
vertex/edge rather than just the string representation that comes
through after the conversion to JSON.