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

      

Then:

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

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:

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

      

History:

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

      

+3


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

      

+3


source


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)

identical(my_output,desired_output)
[1] TRUE

      

+2


source







All Articles