在Ruby中解析JS数组

3
我有一个 JavaScript 文件,其中包含数组对象和数据分配。
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中使用eval js,类似于:

  1. 获取数组名称

  2. 从JS中去除数组初始化

  3. Ruby eval

    A_1_val [0] ='111'

    B_1_txt [0] ='utf8_content'

这两种方式都不太好。也许您可以提出任何想法。

谢谢!


为什么第二种方法很糟糕? - MooGoo
1
约翰逊版本的代码长什么样? - eric
2个回答

2
您可以使用 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]]

johnson-1.2.0/lib/johnson/spidermonkey/runtime.rb:36: [BUG] 分段错误 - OlegZ
听起来你的 johnson 安装出了点问题。上面的代码在我的系统上完美运行。 - eric
您的示例成功执行,但当我尝试使用瑞典语的真实数据时,出现了“[BUG]分段错误”的错误。 - OlegZ
我刚刚更新了代码以包含UTF-8字符。运行更新后的代码是否会导致段错误? - eric
不,它没问题。那http://www.mol.fi/platser/scripts/scripts2.jsp?lang=sv出了什么问题? - OlegZ
我已在Johnson问题跟踪器上提问:http://github.com/jbarnette/johnson/issues/issue/32 - eric

1

谢谢,但这不是我需要的。我正在尝试解析来自第三方服务的JS数组,因此无法更改原始数据格式。我的当前版本是: https://gist.github.com/8ee50a703182cf27c0aa - OlegZ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接