Skip to content

Commit

Permalink
MultiJson::Engines::OkJson.stringify_keys supports Array
Browse files Browse the repository at this point in the history
  • Loading branch information
ishikawa committed May 21, 2011
1 parent e797309 commit 644d1c5
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 7 deletions.
18 changes: 13 additions & 5 deletions lib/multi_json/engines/ok_json.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,19 @@ def self.symbolize_keys(object) #:nodoc:
end

def self.stringify_keys(object) #:nodoc:
return object unless object.is_a?(Hash)
object.inject({}) do |result, (key, value)|
new_key = key.is_a?(Symbol) ? key.to_s : key
new_value = value.is_a?(Hash) ? stringify_keys(value) : value
result.merge! new_key => new_value
case object
when Array
object.map do |value|
stringify_keys(value)
end
when Hash
object.inject({}) do |result, (key, value)|
new_key = key.is_a?(Symbol) ? key.to_s : key
new_value = stringify_keys(value)
result.merge! new_key => new_value
end
else
object
end
end
end
Expand Down
19 changes: 17 additions & 2 deletions spec/multi_json_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,23 @@ def self.encode(string)
end

it 'encodes symbol keys as strings' do
encoded_json = MultiJson.encode({ :foo => { :bar => 'baz' } })
MultiJson.decode(encoded_json).should == { 'foo' => { 'bar' => 'baz' } }
[
[
{ :foo => { :bar => 'baz' } },
{ 'foo' => { 'bar' => 'baz' } }
],
[
[ { :foo => { :bar => 'baz' } } ],
[ { 'foo' => { 'bar' => 'baz' } } ],
],
[
{ :foo => [ { :bar => 'baz' } ] },
{ 'foo' => [ { 'bar' => 'baz' } ] },
]
].each do |example, expected|
encoded_json = MultiJson.encode(example)
MultiJson.decode(encoded_json).should == expected
end
end

it 'encodes rootless JSON' do
Expand Down

0 comments on commit 644d1c5

Please sign in to comment.