From: Gurpal 2000 Date: 2008-09-14T19:19:09+09:00 Subject: Re: json for extjs (without rails) Ara Howard wrote: > On Sep 6, 2008, at 9:06 PM, Gurpal 2000 wrote: > >>> gem install json >> >> thanks >> -- >> Posted via http://www.ruby-forum.com/. >> > > > cfp:~ > cat a.rb > > # i prefer the pure-ruby version of json > # > require 'rubygems' > require 'json' # gem install json_pure OR gem install json > > > # it's easiest to just use mixtures of hash, arrays, strings, and > numbers > # because this translates 1-1 with javascript > # > hash = { 'key' => 42 } > > hash2 = { 'another key' => 42.0 } > > data = [ > hash, hash2 > ] > > puts data.to_json > puts > > > # even if you defined your own classes i personally prefer to > translate to > # 'simple' javascript structures > # > class C > def initialize a, b > @a, @b = a, b > end > > def to_json > { 'a' => @a, 'b' => @b }.to_json > end > end > > puts C.new(4, 2).to_json > > > > > cfp:~ > ruby a.rb > [{"key":42},{"another key":42.0}] > > {"a":4,"b":2} > > > a @ http://codeforpeople.com/ I have another question. If I do something like this: mydata = [ C.new(4, 2).to_json, C.new(1, 3).to_json, C.new(5, 6).to_json ] myhash = { 'data' => mydata } puts myhash.to_json I see that the output will double escape the values (they are actually strings with all sorts of characters in my code). I guess what i need is the to_json on the hash to call to_json in each element of the array. What's the ruby-esque way to do this? I could do it in long code but doesn't feel right. This should easy right? Thanks -- Posted via http://www.ruby-forum.com/.