Skip to content

Instantly share code, notes, and snippets.

@pkoppstein
Created February 11, 2015 22:51
Show Gist options
  • Save pkoppstein/f53658395d04ea884e55 to your computer and use it in GitHub Desktop.
Save pkoppstein/f53658395d04ea884e55 to your computer and use it in GitHub Desktop.
javascript-to-json
#!/usr/bin/env ruby
# Syntax: js2json.rb [PATHNAME]
#
# This ruby script can be used to evaluate a single javascript
# expression (possibly including comments, arithmetic operators, etc.)
# and print the result as a JSON string. This is useful for reading
# JSON-with-comments and javascript-style objects.
#
# The script will read from STDIN if no PATHNAME is specified.
# The output can be converted to JSON using "jq fromjson", as shown in the last example.
#
# Examples:
# Input: /* hello */ [1,1+1]
# Output: "[1,2]"
# Input: {a:1} // a comment
# Output: "{\"a\":1}"
#
# Example using "js2json.rb | jq -c fromjson"
# Input: {a: [1,2]}
# Output: {"a":[1,2]}
require 'json'
require 'execjs'
line=ARGF.read
x = ExecJS.eval( line )
case x
when Array, Hash
p JSON.generate(x)
else
p x.to_json
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment