-1

I have a string in R which escapes quotation marks:

my_text = {\"stim\":[\"platery\",\"denial\",\"generic\"]}

When using cat() I get:

{"stim":["platery","denial","generic"]}

Now my whole string is a JSON string that needs to be parsed and is evaluated invalid by JSONLint. If I copy&paste the cat() version, this is valid a JSON, so I think I just miss some pre-processing here.

I saw this SO post here, and this one, and this really good one, so I tried to replace the single quotation marks with double quotation marks for the JSON parser:

gsub("\\\\", "\\\\\\\\", my_text, fixed=TRUE)

but it did't change my string as I wanted. How can I change the string to become valid JSON?

Community
  • 1
  • 1
ben_aaron
  • 1,504
  • 2
  • 19
  • 39

1 Answers1

0

As Wiktor said your gsub didn't work because you are attempting to replace backslashes, but there aren't any backslashes in your string. R is just using the backslashes as a way to store the double quotes. The third SO post you link does a good job explaining R's string literals which addresses this. A backslash in R is stored as a double backslash.

My first piece of advice would be to use the R package jsonlite to construct your JSON from an R object as opposed to a string if possible (heres the vignette).

Example:

myJSON <- jsonlite::toJSON(list(stim=c("platery","denial","generic")))
# {"stim":["platery","denial","generic"]}

Second, (as the third SO post again does a good job of explaining) copying/pasting the print method of the string may not be the best way to validate the JSON. I'm not sure of the use case, but R storing the double quotes with escape characters is probably not a bad thing.

If you want to get a prettier print method you can use numerous tricks in R (noquote(), cat(), print(quote=F)) but this won't change that R stores the double quotes with backslashes:

Additionally, in some cases constructing the JSON isn't necessary. I have an API built using the plumbr package that returns a list as JSON without any modifications (recJSON <- list(message=messages,recommendations=list(name=names, link=URLs)))

Adam Spannbauer
  • 2,707
  • 1
  • 17
  • 27