3

I've got 2 json objects and want to merge them into one unique objects in R.

Here the content of files:

object 1:

{
    "value": [
        "1",
        "2",
        "3"
    ]
}

object 2:

{
    "value": [
        "4",
        "5",
        "6"
    ]
}

expected results

{
    "value": [
        "1",
        "2",
        "3",
        "4",
        "5",
        "6"
    ]
}

I found similar questions in other language (such as this question), but I 'd like to do that in R (and I use jqr package).

Do you have any idea? Thank you.

2 Answers2

6

To demonstrate @Gregor's advice, here is an example.

# Store JSON content as lists (lst1, lst2)
library(jsonlite);   
lst1 <- fromJSON(txt =
    '{
    "value": [
        "1",
        "2",
        "3"
    ]
}')    
lst2 <- fromJSON(txt =
    '{
    "value": [
        "4",
        "5",
        "6"
    ]
}')

# Merge lst1 and lst2 and output as JSON
toJSON(Map(c, lst1, lst2))
#{"value":["1","2","3","4","5","6"]}

Note, this works for the sample data you provide; if you have multiple keys (perhaps with some keys present in one JSON but not the other), you need to adjust your combination/merging strategy.

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
4

I'm still getting my head around jqr too so there is likely a better, more concise solution without needing the extra paste at the end.

jqr::jq(paste0(js1, js2), ".value[]") %>%     ## extract the 'value's
  combine() %>%                               ## combine to a single JSON
  paste0('{"value":', .,"}")                  ## construct output

  # [1] "{\"value\":[\"1\", \"2\", \"3\", \"4\", \"5\", \"6\"]}"
SymbolixAU
  • 25,502
  • 4
  • 67
  • 139