Module: Billy::JSONUtils

Defined in:
lib/billy/json_utils.rb

Class Method Summary collapse

Class Method Details

.json?(value) ⇒ Boolean

Returns:

  • (Boolean)


5
6
7
8
9
# File 'lib/billy/json_utils.rb', line 5

def self.json?(value)
  !!JSON.parse(value)
rescue JSON::ParserError, TypeError
  false
end

.sort_hash_keys(data) ⇒ Object

Recursively sorts the key/value pairs of all hashes within the given

data structure while preserving the order of arrays.


13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/billy/json_utils.rb', line 13

def self.sort_hash_keys(data)
  return data unless data.is_a?(Hash) || data.is_a?(Array)
  if data.is_a? Hash
    data.keys.sort.reduce({}) do |seed, key|
      seed[key] = sort_hash_keys(data[key])
      seed
    end
  else
    data.map do |element|
      sort_hash_keys(element)
    end
  end
end

.sort_json(json_str) ⇒ Object

Recursively sorts the name/value pairs of JSON objects. For instance,

sort_json('{"b" : "2", "a" : "1"}') == sort_json('{"a" : "1", "b" : "2"}')
Per http://json.org/, "An object is an unordered set of name/value pairs"
and "An array is an ordered collection of values". So, we can sort the
name/value pairs by name (key), but we must preserve the order of an array.
Processing JSON in this way enables a consistent SHA to be derived from
JSON payloads which have the same name/value pairs, but different orders.


34
35
36
# File 'lib/billy/json_utils.rb', line 34

def self.sort_json(json_str)
  JSONUtils.sort_hash_keys(JSON.parse(json_str, symbolize_names: true)).to_json
end