Skip to content

Instantly share code, notes, and snippets.

@geotheory
Created January 31, 2022 13:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geotheory/7e4701e4159239de1c09dfce4bff81b2 to your computer and use it in GitHub Desktop.
Save geotheory/7e4701e4159239de1c09dfce4bff81b2 to your computer and use it in GitHub Desktop.
# function for parsing strings where quotes are not escaped but nested inside triple-quotes
escape_triple_quoted = function(j){
j_split = strsplit(j, '"{3}')[[1]]
f = seq_along(j_split) %% 2 == 0 # filter
j_split[f] = gsub('"', '\\\\"', j_split[f])
paste(j_split, collapse = '"')
}
# Usage
j0 = '[
{
"A" : "no quoted bits"
},
{
"A" : """this contains: "quoted" bits""",
"B" : "no quoted bits"
},
{
"A" : "no quoted bits",
"B" : """this contains: "quoted" and "more quoted" bits"""
}
]'
# clearly this will fail
jsonlite::fromJSON(j0)
#> Error: parse error: after key and value, inside map, I expect ',' or '}'
#> bits" }, { "A" : """this contains: "quoted" bits"""
#> (right here) ------^
escape_triple_quoted(j0) |> jsonlite::fromJSON()
#> A B
#> 1 no quoted bits <NA>
#> 2 this contains: "quoted" bits no quoted bits
#> 3 no quoted bits this contains: "quoted" and "more quoted" bits
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment