Created
March 26, 2021 02:09
-
-
Save mbj/2462dbd967ed6582083c156aa5664397 to your computer and use it in GitHub Desktop.
json to ruby literal
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' | |
require 'unparser' | |
include Unparser::NodeHelpers | |
def mk_hash(hash) | |
s(:hash, *mk_pairs(hash)) | |
end | |
def mk_pairs(hash) | |
hash.map do |key, value| | |
s(:pair, | |
s(:sym, key.to_sym), | |
mk_value(value) | |
) | |
end | |
end | |
def mk_value(value) | |
case value | |
when String | |
s(:str, value) | |
when Array | |
mk_array(value) | |
when Hash | |
mk_hash(value) | |
when Integer | |
s(:int, value) | |
when NilClass | |
s(:nil) | |
when TrueClass | |
s(:true) | |
when FalseClass | |
s(:true) | |
else | |
fail "Not a supported literal: #{value.class}" | |
end | |
end | |
def mk_array(values) | |
s(:array, *values.map(&method(:mk_value))) | |
end | |
puts Unparser.unparse(mk_value(JSON.load_file('response.json'))) |
To make it more generic call:
s(:pair,
mk_value(key),
mk_value(value)
instead of:
s(:pair,
s(:sym, key.to_sym),
mk_value(value)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note it creates symbol keys, was required for my case.