Reputation: 109
I have JSON content that looks like this:
myJSON = '{
"GeneralInputs":
[
{"apples":12,"pears":41},
{"apples":13,"pears":42}
],
"Assumptions":
["jabberwocky.json"]
}'
But what I need is to remove the [
and ]
around ["jabberwocky.json"]
This is dictated by the use of someone else's code downstream.
I've tried ...
..and ...
before = ":[\"jabberwocky.json\"]}"
after = ":\"jabberwocky.json\"}"
str_replace(myJSON, before, after)
How do I do this on just one of the two lists??
BR
Upvotes: 0
Views: 39
Reputation: 389235
You can try -
before = "[\"jabberwocky.json\"]"
after = "jabberwocky.json"
stringr::str_replace(myJSON, fixed(before), after)
#In base R use sub
#sub(before, after, myJSON, fixed = TRUE)
#[1] "{\n\"GeneralInputs\":\n[\n{\"apples\":12,\"pears\":41},\n{\"apples\":13,\"pears\":42}\n],\n\n\"Assumptions\":\njabberwocky.json\n}"
Using cat
for display purpose -
cat(str_replace(myJSON, fixed(before), after))
#{
#"GeneralInputs":
#[
#{"apples":12,"pears":41},
#{"apples":13,"pears":42}
#],
#
#"Assumptions":
#jabberwocky.json
#}
Upvotes: 0
Reputation: 11016
Not sure how generalizable this is, but still:
library(jsonlite)
new_json <- toJSON(fromJSON(myJSON),
auto_unbox = TRUE,
pretty = TRUE)
gives:
{
"GeneralInputs": [
{
"apples": 12,
"pears": 41
},
{
"apples": 13,
"pears": 42
}
],
"Assumptions": "jabberwocky.json"
}
Upvotes: 3