我有一个包含数组对象和数据分配的 js 文件
var A_1_val = new Array(7);
var B_1_txt = new Array(7);
A_1_val[0] = '111';
B_1_txt[0] = 'utf8_content';
A_1_val[1] = '222';
B_1_txt[1] = 'bar';
等..
需要在 ruby 中获取这些数组。
找到 http://github.com/jbarnette/johnson , 但它不能正确返回一个数组对象
另一种方法是在ruby中评估js,类似于
获取数组名
从js切数组初始化
ruby 评估
A_1_val[0] = '111'
B_1_txt[0] = 'utf8_content'
这两种方式都很糟糕。也许你可以提出任何想法
谢谢
最佳答案
您可以使用 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]]
关于javascript - 在ruby中解析js数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3791747/