Saturday, August 15, 2009

JSON in Practice

Writing JSON:

I wrote a specific-purpose JSON writer, in Ruby, to encode the data I needed. It wasn't too tough:


# JSON to send to webdialog
def makeJson( layer_names, scene_names, vis )
ret = '{ '
ret += 'layers:' + makeJsonArr( layer_names )
ret += ', scenes:' + makeJsonArr( scene_names )
ret += ', vis:\"' + vis + '\"'
ret += ' }'
return ret
end

# convert array of names to JSON array
def makeJsonArr( names )
ret = '[ '
start = true
names.each do |n|
unless start
ret += ', '
else
start = false
end
ret += '\"' + n + '\"'
end
ret += ' ]'
return ret
end


Reading JSON:

Since JSON is syntactically correct JavaScript, this is the reader that decodes it in JavaScript:


function rubySays( data ) {
eval( 'obj = ' + data );


The rubySays() method then goes on to make use of the object it creates in its first line. I like code that weighs in at just tens of bytes.

Summary:

Writing JSON is easy. Reading JSON in JavaScript is effortless. Highly recommended!

No comments:

Post a Comment