data_file <-
system.file(package = "rjsoncons", "extdata", "patch_data.json")
## add a biscuit
patch <- '[
{"op": "add", "path": "/biscuits/1", "value": {"name": "Ginger Nut"}}
]'
j_patch_apply(data_file, patch, as = "R") |> str()
## add a biscuit and choose a favorite
patch <- '[
{"op": "add", "path": "/biscuits/1", "value": {"name": "Ginger Nut"}},
{"op": "copy", "path": "/best_biscuit", "from": "/biscuits/2"}
]'
biscuits <- j_patch_apply(data_file, patch)
as_r(biscuits) |> str()
j_patch_from(biscuits, data_file, as = "R") |> str()
if (requireNamespace("jsonlite", quietly = TRUE)) {
## helper for constructing patch operations from R objects
j_patch_op(
"add", path = "/biscuits/1", value = list(name = "Ginger Nut"),
## 'Ginger Nut' is a JSON scalar, so auto-unbox the 'value' argument
auto_unbox = TRUE
)
j_patch_op("remove", "/biscuits/0")
j_patch_op(
"replace", "/biscuits/0/name",
## also possible to unbox arguments explicitly
value = jsonlite::unbox("Chocolate Digestive")
)
j_patch_op("copy", "/best_biscuit", from = "/biscuits/0")
j_patch_op("move", "/cookies", from = "/biscuits")
j_patch_op(
"test", "/best_biscuit/name", value = "Choco Leibniz",
auto_unbox = TRUE
)
## several operations
value <- list(name = jsonlite::unbox("Ginger Nut"))
ops <- c(
j_patch_op("add", "/biscuits/1", value = value),
j_patch_op("copy", path = "/best_biscuit", from = "/biscuits/0")
)
ops
ops <-
j_patch_op("add", "/biscuits/1", value = value) |>
j_patch_op("copy", path = "/best_biscuit", from = "/biscuits/0")
ops
}
Run the code above in your browser using DataLab