3

让我们:

desired_output="{a:'1', b:'foo'}"
D = list(a=1, b="foo")

然后:

out = toJSON(D)
out
"{\"a\":1,\"b\":\"foo\"}"

identical(out, desired_output) # FALSE

是否有更好的功能f(除了gsub),这样它就成立了?

identical( f(toJSON(D)), desired_output) == TRUE

使用cat仅打印到屏幕:

cat(toJSON(D))
{"a":1,"b":"foo"}

背景:

字符串的desired_output格式是使用调用包动态构建 cypher/Neo4j 图形数据库查询所必需的,RNeo4j例如:

# match node n with properties a=1 and b="foo"
RNeo4j::cypher(graph, query="MATCH (n{a:'1', b:'foo'}) RETURN n") 
4

2 回答 2

3

这适用于您的示例,并希望适用于更一般的情况:

gsub("',", "', ",                             # adds spaces after commas
   gsub('"', "'",                             # replaces " with '
      gsub('"([^"]+)":', "\\1:",              # removes " around key names
         toJSON(rapply(D, as.character)))))   # puts " around numerics
# [1] "{a:'1', b:'foo'}"
于 2014-10-03T12:46:14.823 回答
2

一个更简单的解决方案:

## add `'` to each element in the list, then remove any `"` from the json string
my_output <- gsub('"',"",toJSON(rapply(D,function(x)paste0("'",x,"'"))))
## add a space after the comma
my_output <- gsub("',","', ",my_output)

identical(my_output,desired_output)
[1] TRUE
于 2014-10-03T13:04:39.863 回答