Importación de datos de un archivo JSON en R


¿Hay alguna forma de importar datos de un archivo JSON a R? Más específicamente, el archivo es una matriz de objetos JSON con campos de cadena, objetos y matrices. El paquete RJSON no es muy claro sobre cómo lidiar con esto http://cran.r-project.org/web/packages/rjson/rjson.pdf .

 133
Author: user313967, 2010-04-11

7 answers

Primero instale el rjson paquete:

install.packages("rjson")

Entonces:

library("rjson")
json_file <- "http://api.worldbank.org/country?per_page=10&region=OED&lendingtype=LNX&format=json"
json_data <- fromJSON(paste(readLines(json_file), collapse=""))

Actualización: desde la versión 0.2.1

json_data <- fromJSON(file=json_file)
 157
Author: rcs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-08 07:53:38

jsonlite importará el JSON a un marco de datos. Opcionalmente puede aplanar objetos anidados. Los arrays anidados serán marcos de datos.

> library(jsonlite)
> winners <- fromJSON("winners.json", flatten=TRUE)
> colnames(winners)
[1] "winner" "votes" "startPrice" "lastVote.timestamp" "lastVote.user.name" "lastVote.user.user_id"
> winners[,c("winner","startPrice","lastVote.user.name")]
    winner startPrice lastVote.user.name
1 68694999          0              Lamur
> winners[,c("votes")]
[[1]]
                            ts user.name user.user_id
1 Thu Mar 25 03:13:01 UTC 2010     Lamur     68694999
2 Thu Mar 25 03:13:08 UTC 2010     Lamur     68694999
 67
Author: xn.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-04 21:51:32

Un paquete alternativo es RJSONIO. Para convertir una lista anidada, lapply puede ayudar:

l <- fromJSON('[{"winner":"68694999",  "votes":[ 
   {"ts":"Thu Mar 25 03:13:01 UTC 2010", "user":{"name":"Lamur","user_id":"68694999"}},   
   {"ts":"Thu Mar 25 03:13:08 UTC 2010", "user":{"name":"Lamur","user_id":"68694999"}}],   
  "lastVote":{"timestamp":1269486788526,"user":
   {"name":"Lamur","user_id":"68694999"}},"startPrice":0}]'
)
m <- lapply(
    l[[1]]$votes, 
    function(x) c(x$user['name'], x$user['user_id'], x['ts'])
)
m <- do.call(rbind, m)

Da información sobre los votos en su ejemplo.

 29
Author: Karsten W.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-10 12:14:31

Si la URL es https, como se usa para Amazon S3, use getURL

json <- fromJSON(getURL('https://s3.amazonaws.com/bucket/my.json'))
 15
Author: Anthony,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-10 04:44:10

Primero instale el paquete RJSONIO y RCurl:

install.packages("RJSONIO")
install.packages("(RCurl")

Pruebe el siguiente código usando RJSONIO en la consola

library(RJSONIO)
library(RCurl)
json_file = getURL("https://raw.githubusercontent.com/isrini/SI_IS607/master/books.json")
json_file2 = RJSONIO::fromJSON(json_file)
head(json_file2)
 2
Author: Moby M,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-15 11:28:55

Paquetes:

  • biblioteca(httr)
  • biblioteca (jsonlite)

He tenido problemas para convertir json a dataframe/csv. Para mi caso lo hice:

Token <- "245432532532"
source <- "http://......."
header_type <- "applcation/json"
full_token <- paste0("Bearer ", Token)
response <- GET(n_source, add_headers(Authorization = full_token, Accept = h_type), timeout(120), verbose())
text_json <- content(response, type = 'text', encoding = "UTF-8")
jfile <- fromJSON(text_json)
df <- as.data.frame(jfile)

Luego de df a csv.

En este formato debería ser fácil convertirlo a múltiples .csvs si es necesario.

La parte importante es la función de contenido debe tener type = 'text'.

 0
Author: Aaron C,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-19 00:20:15

Para importar, tuve que agregar " marcas:

Json_data

Espero que eso ayude a alguien.

Cormac

 0
Author: Cormac O'Keeffe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-21 09:59:15