获取Json字符串作为R中的命令行参数

mutmk8jj  于 2023-01-18  发布在  其他
关注(0)|答案(1)|浏览(147)

我需要像下面这样传递一个json字符串作为命令行参数,并转换为json对象,然后转换为 Dataframe 。

jsonStr<- '{"a": "1 - 2","b": "2 - 3", "c": "111,222"}'

我将此字符串传递给命令行中的命名参数

Rscript test.R --jsonStr="{"a": "1 - 2","b": "2 - 3", "c": "111,222"}"

获取参数的代码:

option_list = list(
  make_option(c("-b", "--jsonStr"), type="character", default="",
                help="json object", metavar="character"),
  make_option(c("-o", "--output_dir"), type="character", default="",
                help="output_dir", metavar="character")
);
opt_parser = OptionParser(option_list=option_list);
opt = parse_args(opt_parser)
if (is.null(opt)){
  print_help(opt_parser)
  stop("At least one argument must be supplied", call.=FALSE)
}

jsonStr <- opt$jsonStr
output_dir <- opt$output_dir

df <- fromJSON(jsonStr) %>% as.data.frame

当我从命令行运行脚本时,我收到以下错误:

test.R: error: Error in if (j < length(these.flags) & spec[rowmatch, col.has.argument] ==  :
  the condition has length > 1

我错过什么了吗?

dldeef67

dldeef671#

考虑在单引号内使用字符串参数

$ Rscript test_Jan17.R --jsonStr='{"a": "1 - 2","b": "2 - 3", "c": "111,222"}'
  • 输出
Attaching package: ‘dplyr’

The following objects are masked from ‘package:stats’:

    filter, lag

The following objects are masked from ‘package:base’:

    intersect, setdiff, setequal, union

      a     b       c
1 1 - 2 2 - 3 111,222
  • 测试_2017年1月
library(optparse)
library(jsonlite)
library(dplyr)

option_list = list(
  make_option(c("-b", "--jsonStr"), type="character", default="",
              help="json object", metavar="character"),
  make_option(c("-o", "--output_dir"), type="character", default="",
              help="output_dir", metavar="character")
);
opt_parser = OptionParser(option_list=option_list);
opt = parse_args(opt_parser)
if (is.null(opt)){
  print_help(opt_parser)
  stop("At least one argument must be supplied", call.=FALSE)
}

jsonStr <- opt$jsonStr
output_dir <- opt$output_dir

df <- fromJSON(jsonStr) %>% as.data.frame
cat(paste(capture.output(df), collapse = "\n"), "\n")

相关问题