#!/usr/bin/env ruby
require 'json'
class A
def to_json(*a)
{ :a => 'a' }.to_json(*a)
end
end
class B < A
def to_json(*a)
super({ :b => 'b' })
end
end
puts B.new.to_json
produces
{"a":"a"}
How do I get it to produce
{"a":"a", "b":"b"}
in a reasonable way?
I’m using Ruby 1.9.3 and the latest json gem.
A related question is: what are the arguments *a to to_json? I’ve scoured the docs to no avail.
You have two hashes
{:a=>'a'}and{:b=>'b'}in two classes, they’re encapsulated i.e. hidden from outside world. The only way I can see is parse the json string into hash and merge them, then convert the result to json.But here will be small difference: you’re merging
{:a=>'a',:b=>'b'}and got the{"a":"a","b":"b"}*ais parameter to set options for json format