带有双引号

时间:2017-05-30 16:06:00

标签: ruby shell

我想在反引号中传递JSON格式的字符串作为脚本参数,例如:

stats = "[[\"25/01/2017 03:15 PST\",
           \"26/01/2017 03:15 PST\",
           \"27/01/2017 03:15 PST\",
           \"28/01/2017 03:15 PST\"]]"

`my_executable_script.js "#{stats}"`

获得stdout值(这很重要)。问题是JSON参数应该使用双引号进行转义,例如:

my_executable_script.js "[[\"25/01/2017 03:15 PST....."

但执行了my_executable_script.js [[\"25/01/2017 03:15 PST.....]](没有""),这是错误的。我尝试了不同的逃避方法,但没有成功。

我无法使用system()方法,因为我需要执行脚本的结果。

1 个答案:

答案 0 :(得分:7)

使用Shellwords.escape

>> require 'shellwords'
>> puts %x|echo #{Shellwords.escape(stats)}|

[["25/01/2017 03:15 PST",
  "26/01/2017 03:15 PST",
  "27/01/2017 03:15 PST",
  "28/01/2017 03:15 PST"]]
相关问题