Parse js arrays in ruby

I have a js file that contains Array objects and assigns data

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';

etc..

need to get these arrays in ruby.

found http://github.com/jbarnette/johnson but it cannot correctly return an array object

another way is eval js in ruby, similarly

  • get the name of arrays

  • cut arrays initialize from js

  • ruby eval

    A_1_val [0] = '111'

    B_1_txt [0] = 'utf8_content'

both ways are slop. maybe you can offer any ideas

thank

+3
source share
2 answers

You can use a JSON string to marshal data between javascript and 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

which gives the result:

[["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]]
+2
+1

Source: https://habr.com/ru/post/1766496/


All Articles