2013-02-26 15 views
5

Sono nuovo di R e non ho molta esposizione alla programmazione. Sto avendo un problema durante il caricamento di un file (contiene oggetto JSON) in R.Come leggere i dati da un oggetto JSON (in un file) in R?

> library(rjson) 
> jsonFile <- "C:\\Users\\jsonRecords.txt" 
> jsonData <- fromJSON(jsonFile, method = "C", unexpected.escape = "error") 
Error in fromJSON(jsonFile, method = "C", unexpected.escape = "error") : 
    unexpected character 'C' 

ho voluto i dati devono essere letti in R per ulteriori analisi .. Qualsiasi aiuto sarà apprezzato.

Grazie

+0

un'occhiata a 'rjson' http://cran.r-project.org/web/packages/rjson/index.html –

+0

fromJSON (json_str, lima, method = "C" , unexpected.escape = "error") Questo è tutto ciò che ha nel Reference.pdf per importare i dati in R – user1946217

risposta

10

provare solo questo:

fromJSON(file = json_file) 

leggerà tutto il file. qui un esempio:

write(toJSON(iris),'jstest') 
res <- fromJSON(file="jstest") 

str(res) 
List of 5 
$ Sepal.Length: num [1:150] 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ... 
$ Sepal.Width : num [1:150] 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ... 
$ Petal.Length: num [1:150] 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ... 
$ Petal.Width : num [1:150] 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ... 
$ Species  : chr [1:150] "setosa" "setosa" "setosa" "setosa" ... 
+0

Due volte ho visto risposte negative contrassegnate come corrette. +1 –

5

sembra che tutto quello che manca è l'argomento file=

fromJSON(file = json_file, method = "C", unexpected.escape = "error") 

se si guarda al args(fromJSON)

> args(fromJSON) 
function (json_str, file, method = "C", unexpected.escape = "error") 

vedrete che il primo argomento è json_str e il secondo è file. Dato che stai fornendo solo il secondo argomento, devi dire esplicitamente alla funzione che cosa stai dando. (In caso contrario, si pensa che la stringa json_file è un oggetto JSON e cercherà di trattarlo come tale .. da qui l'errore.)

+0

Sì, ho corretto e ho eseguito nuovamente il comando, ma ancora dà lo stesso errore> jsonFile <- "C: \\ Users \\ jsonRecords.txt " > jsonData <- fromJSON (jsonFile, method =" C ", unexpected.escape =" error ") Errore in fromJSON (jsonFile, method =" C ", unexpected.escape =" errore ") : carattere imprevisto 'C' – user1946217

+0

Prova con un altro file, forse un esempio www.json.org Se non hai nessun errore, allora potrebbe esserci qualcosa nel file che causa il problema. Puoi pubblicare il file online? –

+0

Il mio male .. Grazie, legge i dati .. :) – user1946217

Problemi correlati