Skip to content

Instantly share code, notes, and snippets.

@mbj
Created March 26, 2021 02:09
Show Gist options
  • Save mbj/2462dbd967ed6582083c156aa5664397 to your computer and use it in GitHub Desktop.
Save mbj/2462dbd967ed6582083c156aa5664397 to your computer and use it in GitHub Desktop.
json to ruby literal
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')))
@mbj
Copy link
Author

mbj commented Mar 26, 2021

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