i have this code in php:
$n = '[{"area":30,"ind":[5,5,4,5,4.14,3.75],"isCluster":true},{"area":31,"ind":[],"isCluster":false}]';
$command = ""C:Program FilesRR-4.3.0binRscript.exe" C:\xampp\htdocs\CKmeans1D.R $n";
exec($command, $output);
print_r($output);
it execute the CKmeans1D.R to run R file, and in R i have this code:
library(jsonlite)
args <- commandArgs(trailingOnly = TRUE)
x <- fromJSON(args[1])
x
after printing out the output which is the x it error in the php error logs, and this is the error:
Error: lexical error: invalid char in json text.
[{area:30,ind:[5,5,4,5,4.14,3.75]
(right here) ------^
Execution halted
however before adding this line x <- fromJSON(args[1]) i printed out the args[1] and it returns with this:
[{area:30,ind:[5,5,4,5,4.14,3.75],isCluster:true},{area:31,ind:[],isCluster:false}]
the double qoutes are removed in every keys.
how am i able to fix it?
2
Answers
I found a JavaScript code in a gist whose purpose is to fix JSON strings. We can use it with the help of the V8 package to fix your JSON string.
Firstly, copy the JavaScript code below and save it under the name jsonNormalize.js:
Now it is a child game to fix your JSON string with the V8 package:
The double quotes are back!
Maybe this method deserves a small R package. It is useful. Thanks to the author of the gist, David Kaye.
Edit
I’ve just done the package
When building the command in your PHP code, enclose the JSON string
n
with single quotes :Testing without PHP,
argtest.R
:Rscript from command line: