【问题标题】:R - Create string with escaped quotes, with input from variablesR - 创建带有转义引号的字符串,输入来自变量
【发布时间】:2019-06-29 07:00:02
【问题描述】:

为了在 API REST 客户端中使用,我需要创建具有确切内容的字符串。

body =
      "{
        \"epic\":      \"sweden\",
        \"direction\": \"BUY\"
}"

我已经通过创建字符串而不调用变量来使用该解决方案。我现在正在寻找使用来自变量的输入来构建字符串。

我需要一个不添加更多 R 包的解决方案。最好以最小的复杂性获得良好的概览。我希望避免长的正则表达式模式(但如果正则表达式是一个很好的推荐方式,我愿意考虑)。

在 attemp-1 和 try-2 中,我有意省略了大括号,以尽量减少问题及其代码。不过,大括号需要成为解决方案的一部分。

目前的尝试:

Attemp-1(用粘贴解决):

epic1        <- paste0("\"", "sweden")
direction1   <- paste0("BUY", "\"")
create.body1 <- c(epic1, "," ,direction1)

结果:

"\"sweden" ","        "BUY\"" 

问题:每个提供的变量输入都有引号。此外,转义字符仅作为完整字符串的包装添加,而不是按每个键和值的需要添加。

Attemp-2(用 [noQuote] 去掉引号):

epic2        <- paste0("\"", "sweden")
direction2   <- paste0("BUY", "\"")
create.body2 <- noquote(c(epic2, "," ,direction2))

结果:

"sweden ,       BUY"   

问题:所需的转义字符,反斜杠,不见了。

Attemp-3(在构建正文字符串之前预构建 [键/值对]):

# Curly brackets.
curly.bracket.left <- "{"
curly.bracket.right <- "}"

# Epic build [key/pair]
epic_key   <- "\"epic\": "
epic_value <- "\"sweden\""
epic_pair  <- c(epic_key, epic_value)

# Direction build [key/pair]
direction_key   <- "\"direction\": "
direction_value <- "\"BUY\""
direction_pair  <- c(direction_key, direction_value)

# Construct body string.
build.body <- c(
                curly.bracket.left,
                epic_pair,
                direction_pair,
                curly.bracket.right
)

结果:

"{" "\"epic\": " "\"sweden\"" "\"direction\": " "\"BUY\"" "}" 

问题:正文字符串中有很多引号。不过所有 [\"] 都很好。

【问题讨论】:

  • 你试过paste(epic1, "," ,direction1, collapse = "")吗?它输出"\"sweden , BUY\""
  • @LAP:它几乎解决了问题。但是,您的建议将完整的字符串包含在 [\"] 中,同时需要以每个键和值都包含在 [\"] 周围的方式构建正文。
  • 在构建正文字符串之前,我可能需要考虑操作包含其键和对的每个变量。

标签: r quotes double-quotes


【解决方案1】:

我从你的第三次尝试开始。结果看起来像你所追求的。我基本上只是将 c() 切换为 paste() ,并在模板中有空间的地方插入了一些空间。这是你需要的吗?

curly.bracket.left <- "{"
curly.bracket.right <- "}"

# Epic build [key/pair]
epic_key   <- "\"epic\": "
epic_value <- "  \"sweden\","
epic_pair  <- c(epic_key, epic_value)

# Direction build [key/pair]
direction_key   <- "\"direction\": "
direction_value <- "\"BUY\""
direction_pair  <- c(direction_key, direction_value)

# Construct body string.
build.body <- c(
  curly.bracket.left,
  epic_pair,
  direction_pair,
  curly.bracket.right
)

string <- paste(curly.bracket.left, epic_key, epic_value, direction_key, direction_value, curly.bracket.right)

> print(string)
[1] "{ \"epic\":    \"sweden\", \"direction\":  \"BUY\" }" 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 2011-01-02
    相关资源
    最近更新 更多