Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/447.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在ruby中解析js数组_Javascript_Ruby_Arrays_Parsing - Fatal编程技术网

Javascript 在ruby中解析js数组

Javascript 在ruby中解析js数组,javascript,ruby,arrays,parsing,Javascript,Ruby,Arrays,Parsing,我有一个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中获取这些数组 已找到,但无法正确返回数组对象 另一种方法是在ruby中评估js,类似于 获取数组的名称 从js中剪切数组

我有一个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中获取这些数组

已找到,但无法正确返回数组对象

另一种方法是在ruby中评估js,类似于

  • 获取数组的名称

  • 从js中剪切数组初始化

  • ruby eval

    A_1_val[0]=“111”

    B_1_txt[0]=“utf8_内容”

  • 两种方式都很糟糕。也许你可以提出一些建议


    多亏了

    跨语言传递数组(以及许多其他复杂数据结构)的最简单方法是使用JSON。使用此代码使用JavaScript对数组进行编码:

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

    使用以下命令:
    或者:要使用Ruby对其进行解码:

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

    为什么第二种方法很糟糕?约翰逊版本的代码是什么样子的?谢谢,但这不是我需要的。我正在尝试从第三个服务解析js数组,因此无法更改原始数据格式。我当前的版本是:johnson-1.2.0/lib/johnson/spidermonkey/runtime.rb:36:[BUG]分段错误听起来你在安装johnson时遇到了一些有趣的事情。上面的代码在我的系统上运行得很好。您的示例执行成功,但当我尝试瑞典语的真实数据时,得到了“[BUG]分段错误”,我只是更新了代码以包含UTF-8字符。运行更新后的代码是否会导致segfault?否。没关系。那你怎么了
    [["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]]