如何在Ruby中读取JavaScript变量并转为JSON以获取GBP汇率
Alright, let's get this sorted. You've already fetched the raw JavaScript string using Net::HTTP—great start! Now we just need to parse that JS into a Ruby hash (which works just like JSON for easy indexing) so you can grab the GBP rate quickly.
Here are two reliable approaches to do this:
Method 1: Use Regular Expressions + JSON Parsing (No Extra Gems)
This method extracts the Currency.rates object from the JS string, converts it to valid JSON, then parses it into a Ruby hash.
require 'net/http' require 'uri' require 'json' # Fetch the JS file content uri = URI('http://cdn.shopify.com/s/javascripts/currencies.js') response = Net::HTTP.get(uri) # Match the Currency.rates object using regex rates_match = response.match(/Currency\.rates = ({.*?});/) if rates_match # Convert JS object syntax to valid JSON (add quotes around keys) js_rates_str = rates_match[1].gsub(/(\w+):/, '"\1":') # Parse into a Ruby hash rates_hash = JSON.parse(js_rates_str) # Grab the GBP rate gbp_rate = rates_hash['GBP'] puts "GBP exchange rate: #{gbp_rate}" else puts "Oops—couldn't find the Currency.rates object in the response. Double-check the JS file structure!" end
Notes on this method:
- The regex targets the exact pattern
Currency.rates = { ... };to pull out the rate data. - We use
gsubto add double quotes around unquoted keys (since JSON requires quoted keys, but JS allows unquoted ones). - This works if the JS file's structure stays consistent, but might break if Shopify changes how they format the
Currency.ratesvariable.
Method 2: Use ExecJS (More Robust, Handles Edge Cases)
If you want a solution that's less prone to breaking from JS syntax changes, use ExecJS to run the JavaScript directly and extract the Currency.rates object. This requires the execjs gem (which relies on a JS runtime like Node.js—most Ruby environments have this pre-installed).
First install the gem if you haven't:
gem install execjs
Then use this code:
require 'net/http' require 'uri' require 'execjs' # Fetch the JS file content uri = URI('http://cdn.shopify.com/s/javascripts/currencies.js') response = Net::HTTP.get(uri) # Compile and execute the JS, then extract the rates object js_context = ExecJS.compile(response) rates_hash = js_context.eval('Currency.rates') # Get the GBP rate directly from the hash gbp_rate = rates_hash['GBP'] puts "GBP exchange rate: #{gbp_rate}"
Notes on this method:
- ExecJS runs the actual JavaScript code, so it handles any valid JS syntax (like trailing commas, unquoted keys, etc.) that might trip up regex/JSON parsing.
- It's more reliable long-term, even if Shopify tweaks their JS formatting.
Either method will let you access the GBP rate via rates_hash['GBP'] once you've parsed the data. Pick the one that fits your environment and needs!
内容的提问来源于stack exchange,提问作者Asad Shakil

