Windows上的Rscript和jsonlite - 传递包含引号的字符串参数

时间:2016-08-09 13:31:47

标签: json r rscript

(R 3.3.1,Windows 10)

嗨 - 我正在尝试使用以下格式将包含双引号的字符串作为参数传递给r脚本(以便我可以使用toJSON包中的jsonlite将其解析为JSON)从命令提示符:

rscript.exe script.R "argument"

但是,我找不到一种方法来传递包含双引号的参数,方法是脚本正确地看到它。

我用来测试的R脚本是:

library(jsonlite)
args<-commandArgs(trailingOnly=TRUE)
json<-args[1]
print(paste0("Argument received by R as: ", json))
print("JSON validation result:")
validate(json)

我尝试过以下操作但没有成功(即引号总是被删除或者字符串在R中被严重转义):

RScript argTest.R "{""x"":1, ""y"":2}"
RScript argTest.R "{"""x""":1, """y""":2}"
RScript argTest.R "{^"x^":1, ^"y^":2}"
RScript argTest.R "{\"x\":1, \"y\":2}"
RScript argTest.R "{\\\"x\\\":1, \\\"y\\\":2}"

我的测试脚本中的每一个的结果都是:

RScript argTest.R "{""x"":1, ""y"":2}"
Loading required package: methods
[1] "Argument received by R as: {x:1, y:2}"
[1] "JSON validation result:"
[1] FALSE
attr(,"err")
[1] "lexical error: invalid char in json text.\n                                      {x:1, y:2}\n                     (right here) ------^\n"

RScript argTest.R "{"""x""":1, """y""":2}"
Loading required package: methods
[1] "Argument received by R as: {x:1, y:2}"
[1] "JSON validation result:"
[1] FALSE
attr(,"err")
[1] "lexical error: invalid char in json text.\n                                      {x:1, y:2}\n                     (right here) ------^\n"


RScript argTest.R "{^"x^":1, ^"y^":2}"
Loading required package: methods
[1] "Argument received by R as: {^x:1, y:2}"
[1] "JSON validation result:"
[1] FALSE
attr(,"err")
[1] "lexical error: invalid char in json text.\n                                      {^x:1, y:2}\n                     (right here) ------^\n"

RScript argTest.R "{\"x\":1, \"y\":2}"
Loading required package: methods
[1] "Argument received by R as: {x:1, y:2}"
[1] "JSON validation result:"
[1] FALSE
attr(,"err")
[1] "lexical error: invalid char in json text.\n                                      {x:1, y:2}\n                     (right here) ------^\n"

RScript argTest.R "{\\\"x\\\":1, \\\"y\\\":2}"
Loading required package: methods
[1] "Argument received by R as: {\"x\":1, \"y\":2}"
[1] "JSON validation result:"
[1] TRUE

这最后一个看起来很有希望,但如果我尝试将其解析为json,我就不会得到一个有用的对象,因为它似乎是&#34; literalise&#34; (我确定有一个更好的词):

附加代码:

json_parsed<-toJSON(json)
print(json_parsed)
print(json_parsed$x)

结果:

["{\"x\":1, \"y\":2}"]
Error in json_parsed$x : $ operator is invalid for atomic vectors
Calls: print
Execution halted

在生产中,这将在* nix上运行,所以我认为问题将消失(尚待测试),但我需要能够在我的Windows环境中进行测试。

感谢您的帮助。我已经完成了大量搜索这个特定问题,但没有找到任何有用的指针。我不确定这是Windows Shell,Rscript处理,R参数处理还是jsonLite问题。

0 个答案:

没有答案