Let's have:
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
) so that this holds?
identical( f(toJSON(D)), desired_output) == TRUE
Using cat
just prints to the screen:
cat(toJSON(D))
{"a":1,"b":"foo"}
The desired_output
format of the string is required for dynamically constructing cypher/Neo4j graph database queries using RNeo4j
package for a call such as:
# match node n with properties a=1 and b="foo"
RNeo4j::cypher(graph, query="MATCH (n{a:'1', b:'foo'}) RETURN n")
This works on 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'}"