Currently I'm looking to try to get something in a Hash format in Ruby from JS.
I have a JS module that looks something like this
module.exports = {
  key1: "val",
  key2: {
    key3: "val3"
  }
  ...
}
This is given to me as just one string. I'm aware that ExecJS could be helpful here but I'm not sure what the best way to convert it to a Hash would be.
I'm currently trying to do something like this
contents.prepend("var module = {exports: {}};\n")
context = ExecJS.compile contents
context.eval('module.exports').to_hash
But when giving it a string like above I'm getting a parsing error from the JSON gem.
I just tried putting this in a script and running it:
require 'execjs'
str = <<-JS
  // Note, you could just do `var module = {}` here
  var module = {exports: {}};
  module.exports = {
    key1: "val",
    key2: {
      key3: "val3"
    }
  }
JS
context = ExecJS.compile str 
puts context.eval('module.exports').to_hash
# => {"key1"=>"val", "key2"=>{"key3"=>"val3"}}
Maybe you're getting the JSON parse error because the module contains something which can't be serialized.
Here's another approach.
Make a JS file which loads the module and exports it as JSON.
var fs = require('fs');
var hash = require('path/to/my_module.js');
fs.writeFileSync('path/to/output.json', JSON.stringify(hash), 'utf8');
Run that with nodejs my_script.js then read it from Ruby:
require 'json'
hash  = JSON.parse "path/to/output.json"
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With