Saturday, May 12, 2007

json ruby




I'm having a lot of fun with the Ruby JSON library. Here's some documentation

It's really simple to use, and hooks into all the classes that I am using. For example, to turn an Array into JSON:


[1,2,3].to_json


gives:

"[1,2,3]"


To turn a String into an Array and then into JSON (so that you can have simpler Javascript code, and not have to parse the string yourself):


puts "123".split("").to_json
["1","2","3"]


To turn something back into a Ruby object from JSON, use JSON.parse:


a = JSON.parse "123".split("").to_json


gives:


["1", "2", "3"]