From 14e0300c9e309751ae894980efca2de1ae5c6647 Mon Sep 17 00:00:00 2001 From: Xavier Delamotte Date: Sat, 13 Feb 2021 12:56:52 +0000 Subject: [PATCH] Support for symbols --- lib/json/canonicalization.rb | 19 ++++++++++++++++++- spec/c14n_spec.rb | 7 +++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/lib/json/canonicalization.rb b/lib/json/canonicalization.rb index 3967ae9..e972eaf 100644 --- a/lib/json/canonicalization.rb +++ b/lib/json/canonicalization.rb @@ -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(',') + '}' @@ -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 + diff --git a/spec/c14n_spec.rb b/spec/c14n_spec.rb index 5c8df05..f677973 100644 --- a/spec/c14n_spec.rb +++ b/spec/c14n_spec.rb @@ -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