Skip to content

Instantly share code, notes, and snippets.

@Chubek
Last active February 28, 2024 21:48
Show Gist options
  • Save Chubek/60f91a50147103e0c989a9b755376cd9 to your computer and use it in GitHub Desktop.
Save Chubek/60f91a50147103e0c989a9b755376cd9 to your computer and use it in GitHub Desktop.
JSON to S-Expressions
#!/usr/bin/env ruby
# The following script translates a JSON file into S-Expressions. I wrote this after I learned about
# attempts to use Scheme as the lingua franca of Web in the early 90s. Someone told me S-Expressions
# are bascilly XML and well, he's right.
# You can either pass a JSON file as the first argument, or pipe it via STDIN. The translated S-Expression
# data will be written to STDOUT. A regular session would look like:
# cat my_file.json | ruby j2sexp.rb > my_file.sexp
# What is the use of this program? Well, basically, consider this: It's much easier to parse S-Expressions
# that it is to parse JSON. There, I don't need any further explanations!
require 'json'
input_file = ARGV[0]
unless input_file
json_data = STDIN.read
else
json_data = File.read(input_file)
end
parsed_data = JSON.parse(json_data)
def to_sexp_integer(integer)
print "(:integer: #{integer})"
end
def to_sexp_float(float)
print "(:float: #{float})"
end
def to_sexp_string(string)
print "(:string: #{string})"
end
def to_sexp_array(array)
print "(:array: "
array.each do |element|
print " "
to_sexp_element element
print " "
end
print ")"
end
def to_sexp_hash(hash)
print "[:hash: "
hash.each do |key, value|
print "(:key::#{key}:)"
print " "
print "(:value: "
to_sexp_element value
print ")"
end
print "]\n"
end
def to_sexp_element(element)
if element.is_a?(Hash)
to_sexp_hash element
elsif element.is_a?(Array)
to_sexp_array element
elsif element.is_a?(Integer)
to_sexp_integer element
elsif element.is_a?(Float)
to_sexp_float element
elsif element.is_a?(String)
to_sexp_string element
else
print "()"
end
end
to_sexp_hash(parsed_data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment