1

This may seem like a simple problem to solve, but it's beyond me. I have the following enclosed string

'{"foo":"bar","x":"<SOME VAR>"}'

I want to pass a variable into the place of <SOME VAR>. What would be the best way to achieve this? Any help is greatly appreciated.

3
  • 2
    can't you use gsub? string_name <- gsub(pattern = "<SOME VAR>", replacement = variable, x = string_name) where string_name is the name of your example string Commented Jun 22, 2017 at 18:51
  • 1
    Have you tried something like this? y <- 25; paste0('{"foo":"bar","x":"', y, '"}'). Commented Jun 22, 2017 at 19:05
  • 1
    @sweetmusicality That worked perfectly. Can you post that as an answer please? Commented Jun 22, 2017 at 21:21

3 Answers 3

2

(re-posting this as an answer as requested - glad to know it worked!)

can't you use gsub?

string_name <- gsub(pattern = "<SOME VAR>", replacement = variable, x = string_name) 

where string_name is the name of your example string

Sign up to request clarification or add additional context in comments.

Comments

1

Can you store it as a list like:

a <- list("foo" = "bar", "x" = "<SOME VAR>")

If yes you could just fill it using the $operator:

a$x <- 3

Comments

1

Your string is, in fact, a JSON object and thus you can use any JSON parser in R to convert your data to a data.frame, easy to manipulate.

library(jsonlite)

x <- '{"foo":"bar","x":"<SOME VAR>"}'
df <- fromJSON(x)
my_value <- "This is the value I want"
df$x <- my_value
df

#$foo
#[1] "bar"
#
#$x
#[1] "This is the value I want"

You can convert the data.frame again to JSON with:

toJSON(df, auto_unbox = TRUE)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.