Skip to content

Instantly share code, notes, and snippets.

@rajasegar
Created August 27, 2019 01:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajasegar/96ed210eeff5aeabb5cb5edfe85007e0 to your computer and use it in GitHub Desktop.
Save rajasegar/96ed210eeff5aeabb5cb5edfe85007e0 to your computer and use it in GitHub Desktop.
Converting s-exp to json
require 'parser/current'
require 'json'
code = File.read('sample.rb')
ast = Parser::CurrentRuby.parse(code)
#pp ast
@indent = 0
@node_id = 0
def fetch_node_id(node)
case node
when Integer, NilClass, String, Symbol
(@node_id += 1).to_s
else
node.object_id.to_s
end
end
myjson = {}
def traverse(root, node)
node.children.each do |child|
label = case child
when Integer; child
when NilClass; 'nil'
when String; "\"#{child}\""
when Symbol; ":#{child}"
else
child.type.to_s
end
#p "|-#{label}: #{fetch_node_id(child)}"
#@indent += 1
#
location = child.loc.to_hash[:expression] if child.respond_to? :loc
root[fetch_node_id(child)] = {
:label => label,
:loc => location
}
traverse(root[fetch_node_id(child)],child) if child.respond_to? :children
end
end
traverse(myjson, ast)
pp myjson
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment