您可以使用JSON字符串編組的JavaScript和Ruby之間的數據:
#!/usr/bin/env ruby
require 'johnson'
require 'open-uri'
require 'yajl'
# Grab the source to the Javascript JSON implementation
json_js = open('http://www.json.org/json2.js').read
# Strip that silly alert at the top of the file
json_js.gsub!(/^(alert.*)$/, '/* \1 */')
# This is some Javascript you wanted to get something from
some_js = <<-EOF
var A_1_val = new Array(7);
var B_1_txt = new Array(7);
A_1_val[0] = '111';
B_1_txt[0] = 'Ähtäri';
A_1_val[1] = 'Barsebäck slott';
B_1_txt[1] = '新宿區';
EOF
result = Johnson.evaluate(<<-EOF)
/* Include the JSON source code */
#{json_js}
/* Include the source code you wanted to get something from */
#{some_js}
/* Turn the things you wanted out into a string */
JSON.stringify([ A_1_val, B_1_txt ])
EOF
# Get the result back in ruby
ruby_result = Yajl::Parser.parse(result)
# Do something with it
puts ruby_result.inspect
這給輸出:
[["111", "Barseb\303\244ck slott", nil, nil, nil, nil, nil], ["\303\204ht\303\244ri", "\346\226\260\345\256\277\345\214\272", nil, nil, nil, nil, nil]]
爲什麼第二種方法很糟糕? – MooGoo 2010-09-24 23:40:28
johnson版本的代碼是什麼樣的? – eric 2010-09-25 01:14:22