Skip to content

Commit

Permalink
Support for symbols
Browse files Browse the repository at this point in the history
  • Loading branch information
x4d3 authored and gkellogg committed Feb 13, 2021
1 parent dd8c50b commit 14e0300
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
19 changes: 18 additions & 1 deletion lib/json/canonicalization.rb
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,21 @@ def to_json_c14n
end
end

def encode_key(k)
case k
when String
return k.encode(Encoding::UTF_16)
end
k
end

class Hash
# Output JSON with keys sorted lexicographically
# @return [String]
def to_json_c14n
"{" + self.
keys.
sort_by {|k| k.encode(Encoding::UTF_16)}.
sort_by {|k| encode_key(k)}.
map {|k| k.to_json_c14n + ':' + self[k].to_json_c14n}
.join(',') +
'}'
Expand All @@ -81,3 +89,12 @@ def to_json_c14n
self.to_json
end
end

class Symbol
# Output JSON with control characters escaped
# @return [String]
def to_json_c14n
self.to_json
end
end

7 changes: 7 additions & 0 deletions spec/c14n_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,10 @@
end
end
end

describe "special cases for hash keys" do
it "handles hash defined with symbols" do
data = { a: [{b:"b"}] }
expect(data.to_json_c14n).to eq "{\"a\":[{\"b\":\"b\"}]}"
end
end

0 comments on commit 14e0300

Please sign in to comment.