LoginSignup
4
3

More than 3 years have passed since last update.

[Ruby] コマンドライン引数に JSON 文字列を渡す

Last updated at Posted at 2019-05-15

次の Node.js スクリプトを Ruby から実行したい。

hoge.js
const json = process.argv[2];
console.log(json);

const obj = JSON.parse(json);
console.log(obj);

なお Ruby で任意のコマンドを実行する方法は複数あるが、今回は Open3.capture2 を使用する。

方法

コマンドライン引数に JSON 文字列をそのまま渡すと、Node.js 側で正しくパースできない。

require 'json'
require 'open3'

json = { name: '鹿目まどか', age: 14 }.to_json
#=> "{\"name\":\"鹿目まどか\",\"age\":14}"

stdout, _status = Open3.capture2("node hoge.js #{json}")
# SyntaxError: Unexpected token a in JSON at position 1

puts(stdout)
# name:鹿目まどか

そこで JSON 文字列を String#shellescape あるいは Shellwords.#shellescape でエスケープすると、正しく渡すことができる。

require 'json'
require 'open3'
require 'shellwords'

json = { name: '鹿目まどか', age: 14 }.to_json
#=> "{\"name\":\"鹿目まどか\",\"age\":14}"

json.shellescape
#=> "\\{\\\"name\\\":\\\"\\鹿\\目\\ま\\ど\\か\\\",\\\"age\\\":14\\}"

stdout, _status = Open3.capture2("node hoge.js #{json.shellescape}")

puts(stdout)
# {"name":"鹿目まどか","age":14}
# { name: '鹿目まどか', age: 14 }
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3