Reputation: 1
I am fairly new to R, and I have a large folder of JSON files that need to have the trailing comma removed. I have seen a lot of other suggestions in other languages, but would like to keep my code in R.
The trailing comma is the only issue, as I manually deleted it and there were no other errors in the code.
Upvotes: 0
Views: 58
Reputation: 17154
Using this example file with a trailing comma:
writeLines(
'{
"entry1": {
"id": 1,
"language": "en",
}
}',
'file.json'
)
Read the file in as text, use a regex to remove commas followed by }
, write the corrected file back to disk, then read in again as JSON:
library(stringr)
library(jsonlite)
readLines("file.json") |>
paste(collapse = "\n") |>
str_remove_all(",(?=\\n\\s*\\})") |>
writeLines("file_fixed.json")
read_json("file_fixed.json")
Or if you don’t want to save corrected versions to disk, skip that step and use fromJSON()
:
readLines("file.json") |>
paste(collapse = "\n") |>
str_remove_all(",(?=\\n\\s*\\})") |>
fromJSON()
Result:
$entry1
$entry1$id
[1] 1
$entry1$language
[1] "en"
Upvotes: 2