2010-09-24 217 views
3

阵列我持有Array对象和数据分配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'; 

等js文件..

需要在红宝石获得这些阵列。

发现http://github.com/jbarnette/johnson,但它不能正确地返回数组对象

另一种方式是在红宝石的eval JS,类似于

  1. 得到阵列

  2. 切阵列的名称从初始化JS

  3. 红宝石EVAL

    A_1_val [0] = '111'

    B_1_txt [0] = 'utf8_content'

两种方式是吸入。也许你可以提出任何想法

感谢

+0

为什么第二种方法很糟糕? – MooGoo 2010-09-24 23:40:28

+1

johnson版本的代码是什么样的? – eric 2010-09-25 01:14:22

回答

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]] 
+0

约翰逊-1.2.0/lib中/强/ SpiderMonkey的/ runtime.rb:36:[BUG]分段故障 – 2010-09-25 02:04:03

+0

听起来像是你有一些有趣的事情继续你的johnson安装。上面的代码在我的系统上完美运行。 – eric 2010-09-25 02:54:34

+0

您的示例成功执行,但是当我尝试瑞典语中的真实数据时,得到了'[BUG]分段错误' – 2010-09-25 14:16:43

1

最简单的方式传递数组(和许多其他复杂的数据结构)跨语言是JSON。使用它来使用JavaScript对数组进行编码:http://www.json.org/js.html

这将以任何支持JSON的语言可以使用的格式对数组进行编码。

使用此:http://flori.github.com/json/ 或者这样:http://github.com/brianmario/yajl-ruby将它与红宝石解码:

+0

谢谢,但这不是我所需要的。 我想从第三个服务解析js数组,所以不能更改原始数据格式。 我目前的版本是: https://gist.github.com/8ee50a703182cf27c0aa – 2010-09-25 00:30:44