Thies
Thies

Reputation: 33

Create custom JSON with metadata from data.table in R

I've got the following data.table in R:

Date        NumberOfRents  MovingAVG
2019-07-16  166            89.5
2019-07-17  185            100.1

I'm asked to provide a JSON which shall look the following:

labels: ['date1', 'date2', ...],
datasets: [
   {
  label: 'LabelOfDataset',
  borderColor: "rgb(codeRed, codeGreen, codeBlue)",
  borderColor: "rgb(codeRed, codeGreen, codeBlue)",
  fill: false,
  lineTension: 0,
  data: [ { x: 'date1', y1: 'NumberOfRents', y2:'MovingAVG'  }, { x: 'date2', y1: 'NumberOfRents', y2:'MovingAVG' }, ... ]
  }
]

Can I achieve something like that with the function toJSON from the jsonlite-Library?

Upvotes: 0

Views: 177

Answers (1)

Jan
Jan

Reputation: 5264

You will not be able to do it exactly like you asked, because the data structure is not valid JSON. E.g. a JSON name is a string and must be written in "". But you can get pretty close to it.

# Create the data frame
df <- data.frame(Date = c("2019-07-16", "2019-07-17"), 
                 NumberOfRents = c(166, 185),
                 MovingAVG = c(89.5, 100.1))

# Add the data frame to a list containing the rest of the elements
ls <- list(
  labels = c("date1", "date2"), 
  datasets = structure(list(
    label = "LabelOfDataset", 
    borderColor = "rgb(codeRed, codeGreen, codeBlue)", 
    fill = FALSE, 
    lineTension = 0L, 
    data = df)))

# Convert to JSON
toJSON(ls)

That will give you:

{"labels":["date1","date2"],
  "datasets":{
    "label":["LabelOfDataset"],
    "borderColor":["rgb(codeRed, codeGreen, codeBlue)"],
    "fill":[false],
    "lineTension":[0],
    "data":[{"Date":"2019-07-16","NumberOfRents":166,"MovingAVG":89.5},
            {"Date":"2019-07-17","NumberOfRents":185,"MovingAVG":100.1}]
    }
  } 

What is going to get lost is your second "borderColor" element. I think duplicates are not allowed in JSON. You may also notice that the "data" substructure is different. This solution preserves the data and the element names which I assumed is what you intended. If you want xinstead of Date etc. simply change the column names of the data frame.

Upvotes: 1

Related Questions