(R 3.3.1, Windows 10)
Hi - I am trying to pass a string containing double quotes as an argument to an r script (so that I can parse it as JSON using toJSON
from the jsonlite
package) using the following format from the command prompt:
rscript.exe script.R "argument"
However, I cannot find a way to pass an argument that contains double quotes in a way that it is seen correctly by the script.
The R script I'm using to test is:
library(jsonlite)
args<-commandArgs(trailingOnly=TRUE)
json<-args[1]
print(paste0("Argument received by R as: ", json))
print("JSON validation result:")
validate(json)
I have tried the following with no success (i.e. the quotes are always stripped out or the string is badly escaped in 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}"
The results from my test script for each of these are:
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
This final one looked promising, but if I try to parse it as json, I don't get a useful object, as it appears to "literalise" (I'm sure there is a better word) it:
Additional code:
json_parsed<-toJSON(json)
print(json_parsed)
print(json_parsed$x)
result:
["{\"x\":1, \"y\":2}"]
Error in json_parsed$x : $ operator is invalid for atomic vectors
Calls: print
Execution halted
In production, this will be running on *nix so I think the problem will disappear (yet to be tested), but I need to be able to test in my Windows environment.
Thanks for any help. I've done plenty of searching for this specific issue but not found any useful pointers. I'm not sure whether this is a Windows Shell, Rscript processing, R argument handling, or jsonLite issue.