Home > Software engineering >  R/Shiny: JSON Reading Libraries
R/Shiny: JSON Reading Libraries

Time:12-02

I am trying to put "data" into a dataframe but can't figure out an easy way to do this in R. Here is just a snippet from the entire JSON.

[
    {
        "something": 555,
        "timestamp": "aTimeStamp",
        "data": [
            {
                "company": "something1",
                "quarter": 1,

            },
            {
                "company": "something2",
                "quarter": 1,
            }
    }
]

I can do this quite easily in Python utilizing

data = json.load(filepath)
for i in data["data"]:
   //do stuff

But I can't find an easy way to do this in R. All guides I have found look like they are utilizing JSON from a nosql database instead of something like this where we have "something" and "timestamp" included.

UPDATE:

    df_json <- fromJSON(json_data, simplifyDataFrame = TRUE) 
    # get a glimpse of the list_json2 object
    glimpse(df_json)
    glimpse(as.data.frame(df_json["data"])

This code yields $ data <list> [<data.frame[21 x 20]>] but I can't figure out how to take the information found in data and put it in a data frame correctly.

CodePudding user response:

To convert it into a dataframe,you can use unnest() from tidyverse library like,

  library(jsonlite)
  library(tidyverse)
    
  df_json <-fromJSON(json_data, simplifyDataFrame = TRUE) 
  out <- df_json%>% unnest(data) %>% data.frame()
  out

gives,

  something  timestamp    company quarter
1       555 aTimeStamp something1       1
2       555 aTimeStamp something2       1

Data:

[
    {
        "something": 555,
        "timestamp": "aTimeStamp",
        "data": [
            {
                "company": "something1",
                "quarter": 1

            },
            {
                "company": "something2",
                "quarter": 1
            }
    ]
    }
]
  • Related