Created
December 9, 2021 18:02
-
-
Save yzhanginwa/8eaf93e3174e1b8743c220a0b3daa987 to your computer and use it in GitHub Desktop.
To make deep sorted JSON string out of a Ruby Hash, Array, or Scalar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'json' | |
def to_deep_sorted_json(obj) | |
if obj.instance_of?(Array) | |
return '[' + obj.map{|o|to_deep_sorted_json(o)}.join(',') + ']' | |
end | |
if obj.instance_of?(Hash) | |
keys = obj.keys.sort | |
return '{' + keys.map{|k| JSON.generate(k) + ':' + to_deep_sorted_json(obj[k])}.join(',') + '}' | |
end | |
JSON.generate(obj) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment