SteveG
SteveG

Reputation: 109

JSON nest to be removed from just one list

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 ...

https://stackoverflow.com/questions/17164715/how-to-remove-a-level-of-lists-from-a-list-of-lists but this applies to all the lists.

..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

Answers (2)

Ronak Shah
Ronak Shah

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

deschen
deschen

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

Related Questions