【问题标题】:Create string - Remove outer quotes from squared brackets创建字符串 - 从方括号中删除外引号
【发布时间】:2019-12-24 12:25:54
【问题描述】:

我需要创建以下字符串作为有效负载:

    {"url":"http://google.com","number":["123"]}

根据列表 (payload_2) 创建字符串时,我得到以下结果:

 {"url":"http://google.com","number":"[\"123\"]"}

问题:

如何从方括号 (payload_2) 中删除外引号?

解决问题的尝试:

# --------------------------------
# Payload from string (this works).
# --------------------------------

payload_1 <- "{\"url\":\"http://google.com\",\"number\":[\"123\"]}"

# --------------------
# Payload from list (does not work, quotations surrounding squared brackets, still there).
# --------------------

payload_2 <- list(
  "url" = "http://google.com",
  "number" = "[123]"
)

payload_2 <- toJSON(payload_2, auto_unbox = TRUE)  

cat(paste0("payload from string: ", payload_1, "\n"))
cat(paste0("payload from list:   ", payload_2))

# -----------------------------------------
# Test 1 - Using [noquote] - throws errors.
# -----------------------------------------

number <- "[\"123\"]"
number <- noquote(number)

payload_3 <- list(
  "url" = "http://google.com",
  "number" = number
)

payload_3 <- toJSON(payload_3, auto_unbox = TRUE)  

# Error: No method asJSON S3 class: noquote

结果

来自字符串的负载:{"url":"http://google.com","number":["123"]}

来自列表的有效负载:{"url":"http://google.com","number":"[\"123\"]"}

Payload_3:错误:没有方法 asJSON S3 类:noquote

【问题讨论】:

    标签: r json string list payload


    【解决方案1】:

    当你想在 R 中的字符串中使用双引号时,不要使用转义符,而是使用单引号来包裹字符串:

    # These two are equivalent
    number <- "[\"123\"]"
    number <- '["123"]'
    

    此外,当您从包中包含函数时,请告诉我们您正在使用哪些包,这样我们就不必猜测了。我猜你正在使用jsonlite::toJSON。您没有得到想要的结果的原因是因为jsonlite::toJSON 旨在为您提供有效的 JSON 代码,而您想要的输出不是。如果你真的想要,那么你必须在之后使用字符串操作手动调整它。

    payload_2 <- list(
      "url" = "http://google.com",
      "number" = "[123]"
    )
    
    payload_2 <- jsonlite::toJSON(payload_2, auto_unbox = TRUE)  
    
    payload_2a <- stringr::str_replace(payload_2, '\\"\\[', '["')
    payload_2a <- stringr::str_replace(payload_2a, '\\]\\"', '"]')
    

    【讨论】:

      猜你喜欢
      • 2016-04-27
      • 1970-01-01
      • 2012-03-16
      • 2017-09-24
      • 1970-01-01
      • 1970-01-01
      • 2011-11-03
      相关资源
      最近更新 更多