Created
August 27, 2019 01:50
-
-
Save rajasegar/96ed210eeff5aeabb5cb5edfe85007e0 to your computer and use it in GitHub Desktop.
Converting s-exp to json
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 '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