How to access correct column names of dataframe from JSON

685 views Asked by At

I have a simple json string that I read in via a URL.

jsonFile <- jsonlite::fromJSON(RCurl::getURL("http://server.com/jsonData.php"))

[
  {
    "X": "A",
    "Y": 1,
    "Z": 2
  },
  {
    "X": "B",
    "Y": 3,
    "Z": 4
  },
  {
    "X": "C",
    "Y": -4,
    "Z": -3
  },
  {
    "X": "D",
    "Y": -2,
    "Z": -1
  }
]

I am then attempting to color code the columns based on numeric values. Green if column Y or Z is positive and red if negative. I attempted this with the following function:

DT::formatStyle(jsonFile, c('Y', 'Z'), color = 'white', backgroundColor = styleInterval(0, c('green','red')))

But it yields this error: Error in name2int(name, names, rownames) : You specified the columns: X,Y, but the column names of the data are

When I call the names of the dataframe function I get:

names(jsonFile)
[1] "X" "Y"    "Z"  

I think this has to do with how I am accessing the data frame itself since it came from a JSON data structure, but I haven't yet ciphered how to call the column names appropriately. I had the same issue when doing this with piping as well.

Any help is much appreciated.

Thanks

1

There are 1 answers

0
SymbolixAU On

This is not an issue with the JSON-to-data.frame conversion, but rather from the DT formatting you are attempting

From the help file for ?formatStyle

table - a table objet created from datatable()

Therefore, the input to formatStyle needs to be created from the datatable() function. You can do this directly in your function call:

formatStyle(datatable(jsonFile), c('Y', 'Z'), color = 'white', 
          backgroundColor = styleInterval(0, c('green','red')))

enter image description here