Friday, March 6, 2015

R31. Reading json file in R

Using the example json file from wikipedia.


The function fromJSON of jsonlite package is used.


A list is read and we can print what are the components of the list.

# ex31.R
require(jsonlite)
data <- fromJSON("ex31data.json")
for (i in names(data)) {
  print(i)
  cat('class:',class(data[[i]]),'\n')
  cat('length:',length(data[[i]]),'\n\n')
}
print("data[['phoneNumber']]")
print(data[['phoneNumber']])

# [1] "firstName"
# class: character 
# length: 1 
# 
# [1] "lastName"
# class: character 
# length: 1 
# 
# [1] "age"
# class: integer 
# length: 1 
# 
# [1] "address"
# class: list 
# length: 4 
# 
# [1] "phoneNumber"
# class: data.frame 
# length: 2 
# 
# [1] "gender"
# class: list 
# length: 1 
# 
# [1] "data[['phoneNumber']]"
# type       number
# 1 home 212 555-1234
# 2  fax 646 555-4567

No comments:

Post a Comment