First time poster, long time lurker. Be gentle. Moderate R user. I am sure there is a better, functional way to do what I need, but felt like I have researched do death with no insight.
I am trying to merge a data set to a pre-existing JSON structure. Where one row of records per JSON structure for many serialized JSON requests.
I load the data set to data which is 13 variables and change the column headers to match how they appear in the JSON structure
library(jsonlite)
#### Map Column headers to their respective names in the JSON Structure
colnames(data) <- c("default.A",
"default.B",
"default.C",
"items.A",
"items.B.1",
"items.B.2",
"items.B.3",
"items.B.4",
)
Create the blank JSON Structure. This is the format for which the JSON requests need to be handled. Simple nested structure.
sample <- '{
"default": {
"A": "",
"B": "",
"C": "",
},
"items": [{
"A": "",
"B": {
"1": "",
"2": "",
"3": "",
"4": "",
}
}]
}'
jsonstructure <- fromJSON(sample)
set everything as a DF. merge them. Fill NAs with Blanks
x <- as.data.frame(data)
y <- as.data.frame(jsonstructure)
Z <- merge(x, y, all = TRUE)
Z[is.na(Z)] <- ""
Convert to JSON
jsonZ <- toJSON(unname(split(Z, 1:nrow(Z))), pretty=TRUE)
cat(jsonZ)
Current output which does not match
[
[
{
"default.A": "",
"default.B": "1234567890",
"default.C": "",
"items.A": "1234567890",
"items.B.1": "1234",
"items.B.2": "1234",
"items.B.3": "1234",
"items.B.4": "1234",
}
],
[
{
"default.A": "",
"default.B": "0987654321",
"default.C": "",
"items.A": "0987654321",
"items.B.1": "4321",
"items.B.2": "4321",
"items.B.3": "4321",
"items.B.4": "4321",
}
]
]