'import JSON file into a dataframe in R without flattening it

I have a json file formatted like this:

\[
{"rt":5321,"stimulus":"octopus apartment","key_press":78,"word_validity":"practice","trial_type":"html-keyboard-response","time_elapsed":165428,"age":"18","gender":"female","lang":"no","handedness":"right","subject":"57182"},
{"rt":11156,"stimulus":"elephant complaint","key_press":89,"word_validity":"practice","trial_type":"html-keyboard-response","time_elapsed":185936,"age":"18","gender":"female","lang":"no","handedness":"right","subject":"57182"},
...
\]

I want to stack each row like this (for example the column named "rt" is aligned properly): enter image description here

I tried the following code:

install.packages("rjson") 
library("rjson") 
library(dplyr) 
json_file <- "subject-6183ff3ebd3fc.json" 
json_data <- fromJSON(file=json_file) %>% as.data.frame

But the resulting dataframe ended up being flatten. enter image description here

How can I fix the code?



Solution 1:[1]

library(data.table)
library(rjson)
##
#
json = '
[
{"rt":5321,"stimulus":"octopus apartment","key_press":78,"word_validity":"practice","trial_type":"html-keyboard-response","time_elapsed":165428,"age":"18","gender":"female","lang":"no","handedness":"right","subject":"57182"},
{"rt":11156,"stimulus":"elephant complaint","key_press":89,"word_validity":"practice","trial_type":"html-keyboard-response","time_elapsed":185936,"age":"18","gender":"female","lang":"no","handedness":"right","subject":"57182"}
]
'
##
#   using data.table
#   - result is data.table
#
result <- rbindlist(lapply(fromJSON(json), as.data.table))
##
#   using base R
#   - result is data.frame
#
result <- do.call(rbind, lapply(fromJSON(json), as.data.frame))
##
#   from comment
#   - result is a matrix (so all numeric are converted to character)
#   - might not be what you want...
#
result <- do.call(rbind, fromJSON(json))
##

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jlhoward