Rjson: convert `list` to JSON-like string compatible with Cypher DSL

Let be:

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



out = toJSON(D)

identical(out, desired_output) # FALSE


Is there a better function f

(other than gsub

) to make this work?

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


Usage cat

just prints to screen:




The string format desired_output

is required to dynamically build cypher / Neo4j graph database queries using a package RNeo4j

to call, for example:

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



source to share

2 answers

This works for your example and hopefully more general cases:

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'}"




A little simpler:

## 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)

[1] TRUE




All Articles