序列化JSON OpenStruct中的连字符

时间:2017-07-28 10:34:26

标签: ruby

我有一个JSON对象,例如:

"c": {
    "10-20": 9.0,
    "0-10": 8.5,
    "30-end": 5.085714285714286,
    "20-30": 10.3
}

当我使用以下命令将JSON转换为序列化对象时

JSON.parse(response.body, object_class: OpenStruct)

它给了我:

<OpenStruct 10-20=0, 0-10=8.5, 30-end=5.085714285714286, 20-30=10.3>

当然,不能用c.10-20访问,因为我不相信连字符是有效的类变量名。那么,你如何访问这些值呢?

1 个答案:

答案 0 :(得分:2)

您可以像使用哈希一样使用方括号:

# a generic method
termLabels <- function(object, ...) {
    UseMethod("termLabels")
}
# add for the train object too to save typing
termLabels.train <- function(object, ...) {
    attr(formula(object), "term.labels")
}
# try to find term labels for cv.glmnet object
# lambda must be provided and snaps to search grid
# allowed column names must be provided from corresponding data object
termLabels.cv.glmnet <- function(object, lambda, names, ...) {
    if (missing(lambda)) { stop("lambda is missing") }
    if (missing(names)) { stop("names is missing") }
    # match lambda
    lambdaArray <- object$glmnet.fit$a0
    if (lambda > max(lambdaArray) || lambda < min(lambdaArray)) {
        stop(paste("lambda must be in range", 
            paste(range(lambdaArray), collapse = ":")))
    }
    # find closest lambda
    whichLambda <- which.min(abs(lambdaArray - lambda))
    message(paste("using lambda", lambdaArray[whichLambda]))
    # matrix of parameter estimates
    betaLambda <- object$glmnet.fit$beta[, whichLambda, drop = FALSE]
    # non-zero estimates
    betaLambda <- betaLambda[betaLambda[, 1] != 0, , drop = FALSE]
    vars <- rownames(betaLambda)
    # search with names as pattern
    # note, does not account for nested names, e.g. var1 and var11
    matchNames <- apply(matrix(names), MARGIN = 1, FUN = grepl, x = vars)
    names[apply(matchNames, MARGIN = 2, FUN = any)]
}
termLabels(glmnet1, lambda = 1, names = colnames(df))
# using lambda 0.998561314952713
# [1] "var1" "var2"

当然,如果大多数密钥都不是有效的方法名称,那么你也可以使用哈希而不用obj["10-20"] #=> 0

相关文档: OpenStruct#[]