2010-09-24 147 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